Best Python code snippet using playwright-python
ParseRunEvent.py
Source:ParseRunEvent.py  
1import os, sys, inspect, subprocess2from multiprocessing import Pool34class Event: # interface5    def run (self):6        pass78    def parse_command (self, command: str, exit_sequence: tuple) -> tuple:9        pass1011    def astype (self):12        pass1314    @staticmethod15    def map_type (expected_event, type_hint: str):16        if isinstance(expected_event, Event):17            return expected_event.astype(type_hint)1819        if isinstance(expected_event, str):20            return CommandParser.type_map[type_hint](21                    expected_event)2223        return expected_event2425    @staticmethod26    def run_event (expected_event):27        if isinstance(expected_event, Event):28            return expected_event.run()2930        return expected_event3132class ListEvent(list, Event):33    def __init__ (self, *args, multiprocess=False):34        super(ListEvent, self).__init__(*args)35        self.multiprocess = multiprocess3637    def run (self) -> list:38        if self.multiprocess:39            return Pool(os.cpu_count()).map(Event.run_event, self)40        41        return [ Event.run_event(subevent) for subevent in self ]4243    def parse_command (self, command: str, exit_sequences: tuple,44            parse_trace: bool = True, stdout_indent: int = 0) -> tuple:45        if parse_trace: ParseTrace.parse_input("ListEvent", command, 46                stdout_indent)4748        command = command.strip()49        assert command[0] == "["50        command = command[1::].strip()5152        exit_sequence = None53        while command and exit_sequence != "]":54            if command[0] == "]":55                command = command[1::].strip()56                break5758            if command[0:2] == "--":59                setting, exit_sequence, command = CommandParser.parse_next(60                        command[2::], (" ", ",", "]"), parse_trace,61                        stdout_indent + 1)6263                if parse_trace: ParseTrace.set_event_setting(setting, stdout_indent)64                setattr(self, setting, True)65                continue6667            # event setting flag68            subevent, exit_sequence, command = CommandParser.parse_next(69                    command, (",", "]"), parse_trace, stdout_indent + 1)7071            if parse_trace: ParseTrace.append_subevent(subevent, stdout_indent)72            self.append(subevent)73            74        if command[0:2] == "->":75            type_hint, exit_sequence, command = CommandParser.parse_next(76                command[2::], exit_sequences, parse_trace, stdout_indent + 1)77            78            if parse_trace: ParseTrace.trace(f"   BROADCAST_TYPE = {type_hint}",79                    stdout_indent)80            self.astype(type_hint.strip())8182        else:83            white_space, exit_sequence, command = CommandParser.parse_next(84                command, exit_sequences, parse_trace=False)85        86        if parse_trace: ParseTrace.parse_output(self, command, stdout_indent)87        return self, exit_sequence, command8889    def astype (self, type_hint):90        # broadcasting of types91        self = ListEvent([ Event.map_type(subevent, type_hint) for subevent 92                in self ], multiprocess=self.multiprocess)9394class MapEvent (dict, Event):95    def __init__ (self, *args, **kwargs):96        super(MapEvent, self).__init__(*args, **kwargs)9798    def run (self) -> dict:99        return {100            Event.run_event(key_subevent): Event.run_event(arg_subevent)101            for key_subevent, arg_subevent in self.items()102        }103104    def parse_command (self, command: str, exit_sequences: tuple, parse_trace: bool,105            stdout_indent: int = 0) -> tuple:106        if parse_trace: ParseTrace.parse_input("MapEvent", command, 107                stdout_indent)108109        command = command.strip()110        assert command[0] == "{"111        command = command[1::].strip()112113        exit_sequence = None114        while command and exit_sequence != "}":115            if command[0] == "}":116                command = command[1::].strip()117                break118119            if command[0:2] == "--":120                setting, exit_sequence, command = CommandParser.parse_next(121                        command[2::], (" ", ",", "}"), parse_trace,122                        stdout_indent + 1)123124                if parse_trace: ParseTrace.set_event_setting(setting, stdout_indent)125                setattr(self, setting, True)126                continue127        128            key_subevent, exit_sequence, command = CommandParser.parse_next(129                    command, (":"), parse_trace, stdout_indent + 1)130            arg_subevent, exit_sequence, command = CommandParser.parse_next(131                    command, (",", "}"), parse_trace, stdout_indent + 1)132            133            if parse_trace: ParseTrace.append_subevent(f" [{key_subevent}]:{arg_subevent}",134                    stdout_indent)135                136            self[key_subevent] = arg_subevent137138        if command[0:2] == "->":139            type_hint, exit_sequence, command = CommandParser.parse_next(140                command[2::], exit_sequences, parse_trace, stdout_indent + 1)141142            if parse_trace: ParseTrace.trace(f"   BROADCAST_TYPE = {type_hint}",143                    stdout_indent)144145            self.astype(type_hint.strip())146        else:147            white_space, exit_sequence, command = CommandParser.parse_next(148                command, exit_sequences, parse_trace=False)149        150        return self, exit_sequence, command151152    def astype (self, type_hint):153        # type_hint not compatible with event type map154        if (type_hint[0] != "(" or type_hint[-1] != ")" or 155                "," not in type_hint):156            return157158        type_hint = type_hint[1:-1].split(",")159        self =MapEvent(**{160            Event.map_type(key_subevent, type_hint[0].strip()): 161            Event.map_type(arg_subevent, type_hint[1].strip())162            for key_subevent, arg_subevent in self163        })164165class FunctionEvent (Event):166    def __init__ (self, function=None):167        super(FunctionEvent, self).__init__()168        self.function = function169        self.args = ListEvent()170        self.kwargs = MapEvent()171172    def run (self):173        return self.function(*Event.run_event(self.args), 174                **Event.run_event(self.kwargs))175176    def parse_command(self, command: str, exit_sequences: tuple,177            parse_trace: bool = True, stdout_indent: int = 0, 178            wrapper_function=None) -> tuple:179180        if parse_trace: ParseTrace.parse_input("FunctionEvent FROM_"181                + (f"WRAPPER:{wrapper_function}" if wrapper_function else "CMD"),182                command, stdout_indent)183184        if not wrapper_function:185            command = command.strip()186            assert command[0:5] == "<run:"187            function_sequence = command[5:command.find(">")].strip()188189            if "." not in function_sequence:190                self.function = getattr(sys.modules[__name__], function_sequence)191            else:192                function_sequence = function_sequence.split(".")193                self.function = __import__(function_sequence[0].strip())194195                for member in function_sequence[1::]:196                    self.function = getattr(self.function, member)197198            command = command[command.find(">") + 1::].strip()199            if parse_trace: ParseTrace.trace(f"   SET_FUNCTION = {self.function}",200                    stdout_indent)201        else:202            self.function = wrapper_function203204        exit_sequence = None205        while command and exit_sequence != "</run>":206            if command[0:6] == "</run>":207                command = command[6::].strip()208                break209210            if command[0:2] == "--":211                setting, exit_sequence, command = CommandParser.parse_next(212                        command[2::], (" ", ",", "</run>"), parse_trace, 213                        stdout_indent + 1)214215                if parse_trace: ParseTrace.set_event_setting(setting, stdout_indent)216                setattr(self, setting, True)217                continue218219            if command[0] == "-":220                key = command[1:command.find("=")].strip()221                subevent, exit_sequence, command = CommandParser.parse_next(222                        command[command.find("=") + 1::].strip(), (",", "</run>"),223                        parse_trace, stdout_indent + 1)224225                if parse_trace: ParseTrace.append_subevent(f"KWARG: {key} = {subevent}",226                        stdout_indent)227                self.kwargs[key] = subevent228            else:229                subevent, exit_sequence, command = CommandParser.parse_next(230                        command, (",", "</run>"), parse_trace, stdout_indent + 1)231232                if parse_trace: ParseTrace.append_subevent(f"ARG: {subevent}",233                        stdout_indent)234                self.args.append(subevent)235236        white_space, exit_sequence, command = CommandParser.parse_next(237                command, exit_sequences, parse_trace=False)238        239        if parse_trace: ParseTrace.parse_output(self, command, stdout_indent)240        return self, exit_sequence, command241242    def astype (self, type_hint):243        # no type broadcasting allowed244        pass245246class TryEvent (Event):247    def __init__ (self, exit_precedent: bool =False):248        super(TryEvent, self).__init__()249        self.precedent = None250        self.exception = None251252    def run (self):253        try:254            return Event.run_event(self.precedent)255        except:256            return Event.run_event(self.exception)257258    def parse_command(self, command: str, exit_sequences: tuple = (","),259            parse_trace: bool = True, stdout_indent: int = 0):260        if parse_trace: ParseTrace.parse_input("TryEvent", command, 261                stdout_indent)262263        command = command.strip()264        if command[0:5] == "<try>": command = command[5::].strip()265266        exit_sequence = ""        267        while command and self.precedent is None and exit_sequence != "</try>":268            if command[0:6] == "</try>":269                command, exit_sequence = command[6::], "</try>"270                break271272            if command[0:2] == "--":273                setting, exit_sequence, command = CommandParser.parse_next(274                        command[2::], (" ", ",", "</truy>"), parse_trace, 275                        stdout_indent + 1)276277                if parse_trace: ParseTrace.set_event_setting(setting, stdout_indent)278                setattr(self, setting, True)279                continue280281            precedent, exit_sequence, command = CommandParser.parse_next(282                    command, (",", "</try>"), parse_trace, stdout_indent + 1)283284            if parse_trace: ParseTrace.trace(f"   SET PRECEDENT = {precedent}",285                    stdout_indent)286            self.precedent = precedent287288        if exit_sequence != "</try>":289            self.exception = TryEvent()290            exception, exit_sequence, command = self.exception.parse_command(291                command, exit_sequences, parse_trace, stdout_indent + 1)292293            if parse_trace: ParseTrace.trace(f"   SET EXCEPTION = {exception}",294                    stdout_indent)295            self.exception = exception296        else:297            white_space, exit_sequence, command = CommandParser.parse_next(298                    command, exit_sequences, parse_trace=False)299        300        if parse_trace: ParseTrace.parse_output(self, command, stdout_indent)301        return self, exit_sequence, command302303    def astype(self, type_hint: str):304        pass305306307class MainProcess (ListEvent):308    def __init__ (self, *args, multiprocess=False, spawn_subprocess=False, 309            subprocess_newconsole=False, parse_trace=False, run_trace=False):310311        super(MainProcess, self).__init__(*args,312                multiprocess=multiprocess)313314        self.spawn_subprocess = spawn_subprocess315        self.parse_trace = parse_trace316        self.run_trace = run_trace317        self.subprocess_newconsole = subprocess_newconsole318319    def spawn_runsubprocess (self, command: str) -> None:320        '''321        '''322        command = [ "EventSubprocess.bat", sys.executable,323                " " + command + " ", "-" ]324        325        if self.parse_trace:    command.append("--parse_trace")326        if self.run_trace:      command.append("--run_trace")327        if self.subprocess_newconsole:328            spawn = subprocess.Popen(command, cwd=os.getcwd(),329                    creationflags=subprocess.CREATE_NEW_CONSOLE)330        else:331            command[3] = "RESPAWN"332            spawn = subprocess.Popen(command, cwd=os.getcwd())333        334        stdout, stderr = spawn.communicate()335        sys.exit(spawn.returncode)336337    def parse_process_params (self, *sysargs) -> tuple:338        commands = []339340        for sysarg in sysargs:341            if sysarg[0:2] == "--":342                setattr(self, sysarg[2::].strip(), True)343            else:   commands.append(sysarg)344        345        return ",".join(commands)346347    @staticmethod348    def parserun_from_cmd (*sysargs) -> None:349        process = MainProcess()350        command = process.parse_process_params(*sysargs)351352        if process.spawn_subprocess:353            process.spawn_runsubprocess(command)354355        process, exit_sequence, exit_command = process.parse_command(356            CommandParser.encrypt("[" + command + "]"), (","),357            parse_trace=process.parse_trace, stdout_indent=0)358359        sys.exit(process.run())360    361class CommandParser:362    encryption_map = {363      "(": "%(%",    ")": "%)%",364      ",": "%,%",    "-": "%-%",365      ":": "%:%",    ">": "%>%",366      "[": "%[%",    "]": "%]%",367      "{": "%{%",   "}": "%}%"368    }369370    type_map = {371      "str":    lambda char: str(char),372      "int":    lambda num: int(num),373      "float":  lambda num: float(num),374      "bool":   lambda exp: (exp != "False" and exp != "")375    }376377    @staticmethod378    def encrypt (command: str) -> str:379        '''380        '''381        encrypted_command, protected = "", False382383        for char in command:384            if char == "`":385                protected = not protected386                continue387            388            if protected and char in CommandParser.encryption_map:389                char = CommandParser.encryption_map[char]390391            encrypted_command += char392393        return encrypted_command394395    @staticmethod396    def decrypt (command: str) -> str:397        for protected_char, encrypted_sequence in CommandParser.encryption_map.items():398            command = command.replace(encrypted_sequence, protected_char)399400        return command401402    @staticmethod403    def parse_next (command: str, exit_sequences: tuple, parse_trace: bool = True,404            stdout_indent: int = 0):405        '''406            greedy-recursive algorithm.407            returns408                out: tuple in the sequence of <parsed_event_object> 409                    <exit_sequence> <command_remainder>410        '''411        command = command.strip()412        if not len(command): return "", "", ""413414        if command[0:5] == "<run:":415            return FunctionEvent().parse_command(command,416                    exit_sequences, parse_trace, stdout_indent)417        418        if command[0:5] == "<try>":419            return TryEvent().parse_command(command, exit_sequences,420                    parse_trace, stdout_indent)421422        if command[0] == "[":423            return ListEvent().parse_command(command,424                    exit_sequences, parse_trace, stdout_indent)425426        if command[0] == "{":427            return MapEvent().parse_command(command,428                    exit_sequences, parse_trace, stdout_indent)429430        # var argument ***********************************************431        exit_indices = [ command.find(sequence) for sequence 432                in exit_sequences ]433434        mindex = min([ len(command) if exit_index < 0 else exit_index for435                exit_index in exit_indices ])436        437        exit_sequence = (exit_sequences[exit_indices.index(mindex)] if438            mindex != len(command) else "")439440        event = CommandParser.decrypt(command[0:mindex].strip())441442        if "->" in event:443            event = event.split("->")444            event = CommandParser.type_map[event[1].strip()](445                    event[0].strip())446447        command = command[mindex + len(exit_sequence)::].strip()448449        if parse_trace: ParseTrace.parse_output(event, command, stdout_indent)450        return (event, exit_sequence, command)451452class ParseTrace ():453    @staticmethod454    def parse_input (event_type: str, command: str, stdout_indent: int = 0):455        ParseTrace.trace(f"*  PARSING {event_type}.", stdout_indent)456        ParseTrace.trace(f"   INPUT_CMD: {command}", stdout_indent)457458    @staticmethod459    def append_subevent (subevent, stdout_indent: int = 0):460        ParseTrace.trace(f"   APPEND {subevent}.", stdout_indent)461462    @staticmethod463    def set_event_setting (setting: str, stdout_indent: int = 0):464        ParseTrace.trace(f"   SET EVENT_SETTING: {setting}", stdout_indent)465466    @staticmethod467    def parse_output (event: Event, command: str, stdout_indent: int = 0):468        ParseTrace.trace(f"/* PARSED {event}.", stdout_indent)469        ParseTrace.trace(f"   OUTPUT_CMD: {command}", stdout_indent)470471    @staticmethod472    def trace (message: str, stdout_indent: int = 0):473        print(f"{'   ' * stdout_indent}{message}")474475# function decorator476def parsable_from_cmd (function, spawn_subprocess=False,477        subprocess_newconsole=False):478479    def wrapped_function(*args, **kwargs):480        redirected_from = inspect.stack()[1]481482        if redirected_from[3] != "<module>": 483            return function(*args, **kwargs)484485        process = MainProcess(spawn_subprocess=spawn_subprocess,486                subprocess_newconsole=subprocess_newconsole)487        488        command = process.parse_process_params(*sys.argv[1::])489        if process.spawn_subprocess:490            491            process.spawn_runsubprocess("<run:" + function.__module__492                    + "." + function.__name__ + ">" + command493                    + "</run>")494495        function_event, exit_sequence, exit_command = FunctionEvent().parse_command(496                CommandParser.encrypt(command), exit_sequences=(","),497                parse_trace = process.parse_trace, stdout_indent=0,498                wrapper_function=function)499500        sys.exit(function_event.run())501502    return wrapped_function503504if __name__ == "__main__":505    process = MainProcess.parserun_from_cmd(*sys.argv[1::])
...test_schedule.py
Source:test_schedule.py  
...81        for node in state.worklist:82            assert node.count == 183        # must return here, then the test passed84    def test_split_pack(self):85        loop1 = self.parse_trace("""86        f10 = raw_load_f(p0, i0, descr=double)87        f11 = raw_load_f(p0, i1, descr=double)88        f12 = raw_load_f(p0, i2, descr=double)89        """)90        ps = PackSet(16)91        ps.packs = [self.pack(loop1, 0, 3)]92        op1 = ps.packs[0].operations[0]93        op2 = ps.packs[0].operations[1]94        ps.split_overloaded_packs(self.vector_ext)95        assert len(ps.packs) == 196        assert ps.packs[0].leftmost() is op1.getoperation()97        assert ps.packs[0].rightmost() is op2.getoperation()98    def test_schedule_split_load(self):99        loop1 = self.parse_trace("""100        f10 = raw_load_f(p0, i0, descr=float)101        f11 = raw_load_f(p0, i1, descr=float)102        f12 = raw_load_f(p0, i2, descr=float)103        f13 = raw_load_f(p0, i3, descr=float)104        f14 = raw_load_f(p0, i4, descr=float)105        f15 = raw_load_f(p0, i5, descr=float)106        """)107        pack1 = self.pack(loop1, 0, 6)108        loop2 = self.schedule(loop1, [pack1])109        loop3 = self.parse_trace("""110        v10[4xi32] = vec_load_f(p0, i0, 1, 0, descr=float)111        f10 = raw_load_f(p0, i4, descr=float)112        f11 = raw_load_f(p0, i5, descr=float)113        """, False)114        self.assert_equal(loop2, loop3)115    @py.test.mark.skipif("not platform.machine().startswith('x86')")116    def test_int_to_float(self):117        loop1 = self.parse_trace("""118        i10 = raw_load_i(p0, i0, descr=long)119        i11 = raw_load_i(p0, i1, descr=long)120        i12 = int_signext(i10, 4)121        i13 = int_signext(i11, 4)122        f10 = cast_int_to_float(i12)123        f11 = cast_int_to_float(i13)124        """)125        pack1 = self.pack(loop1, 0, 2)126        pack2 = self.pack(loop1, 2, 4)127        pack3 = self.pack(loop1, 4, 6)128        loop2 = self.schedule(loop1, [pack1, pack2, pack3])129        loop3 = self.parse_trace("""130        v10[2xi64] = vec_load_i(p0, i0, 1, 0, descr=long)131        v20[2xi32] = vec_int_signext(v10[2xi64], 4)132        v30[2xf64] = vec_cast_int_to_float(v20[2xi32])133        """, False)134        self.assert_equal(loop2, loop3)135    def test_scalar_pack(self):136        loop1 = self.parse_trace("""137        i10 = int_add(i0, 73)138        i11 = int_add(i1, 73)139        """)140        pack1 = self.pack(loop1, 0, 2)141        loop2 = self.schedule(loop1, [pack1], prepend_invariant=True)142        loop3 = self.parse_trace("""143        v10[0xi64] = vec_i()144        v20[1xi64] = vec_pack_i(v10[2xi64], i0, 0, 1)145        v30[2xi64] = vec_pack_i(v20[2xi64], i1, 1, 1)146        v40[2xi64] = vec_expand_i(73)147        #148        v50[2xi64] = vec_int_add(v30[2xi64], v40[2xi64])149        """, False)150        self.assert_equal(loop2, loop3)151        loop1 = self.parse_trace("""152        f10 = float_add(f0, 73.0)153        f11 = float_add(f1, 73.0)154        """)155        pack1 = self.pack(loop1, 0, 2)156        loop2 = self.schedule(loop1, [pack1], prepend_invariant=True)157        loop3 = self.parse_trace("""158        v10[0xf64] = vec_f()159        v20[1xf64] = vec_pack_f(v10[2xf64], f0, 0, 1)160        v30[2xf64] = vec_pack_f(v20[2xf64], f1, 1, 1)161        v40[2xf64] = vec_expand_f(73.0)162        #163        v50[2xf64] = vec_float_add(v30[2xf64], v40[2xf64])164        """, False)165        self.assert_equal(loop2, loop3)166    def test_scalar_remember_expansion(self):167        loop1 = self.parse_trace("""168        f10 = float_add(f0, f5)169        f11 = float_add(f1, f5)170        f12 = float_add(f10, f5)171        f13 = float_add(f11, f5)172        """)173        pack1 = self.pack(loop1, 0, 2)174        pack2 = self.pack(loop1, 2, 4)175        loop2 = self.schedule(loop1, [pack1, pack2], prepend_invariant=True)176        loop3 = self.parse_trace("""177        v10[0xf64] = vec_f()178        v20[1xf64] = vec_pack_f(v10[2xf64], f0, 0, 1)179        v30[2xf64] = vec_pack_f(v20[2xf64], f1, 1, 1)180        v40[2xf64] = vec_expand_f(f5) # only expaned once181        #182        v50[2xf64] = vec_float_add(v30[2xf64], v40[2xf64])183        v60[2xf64] = vec_float_add(v50[2xf64], v40[2xf64])184        """, False)185        self.assert_equal(loop2, loop3)186    def find_input_arg(self, name, loop):187        for arg in loop.inputargs:188            if str(arg).startswith(name):189                return arg190        raise Exception("could not find %s in args %s" % (name, loop.inputargs))191    def test_signext_int32(self):192        loop1 = self.parse_trace("""193        i10 = int_signext(i1, 4)194        i11 = int_signext(i1, 4)195        """, additional_args=['v10[2xi64]'])196        pack1 = self.pack(loop1, 0, 2)197        var = loop1.inputargs[-1]198        vi = VectorizationInfo(None)199        vi.datatype = 'i'200        vi.bytesize = 8201        vi.count = 2202        vi.signed = True203        var.set_forwarded(vi)204        loop2 = self.schedule(loop1, [pack1], prepend_invariant=True,205                              overwrite_funcs = {206                                'getvector_of_box': lambda v: (0, var),207                              })208        loop3 = self.parse_trace("""209        v11[2xi32] = vec_int_signext(v10[2xi64], 4)210        """, False, additional_args=['v10[2xi64]'])211        self.assert_equal(loop2, loop3)212    @py.test.mark.skipif("not platform.machine().startswith('x86')")213    def test_cast_float_to_int(self):214        loop1 = self.parse_trace("""215        f10 = raw_load_f(p0, i1, descr=double)216        f11 = raw_load_f(p0, i2, descr=double)217        f12 = raw_load_f(p0, i3, descr=double)218        f13 = raw_load_f(p0, i4, descr=double)219        f14 = raw_load_f(p0, i5, descr=double)220        f15 = raw_load_f(p0, i6, descr=double)221        f16 = raw_load_f(p0, i7, descr=double)222        f17 = raw_load_f(p0, i8, descr=double)223        #224        i10 = cast_float_to_int(f10)225        i11 = cast_float_to_int(f11)226        i12 = cast_float_to_int(f12)227        i13 = cast_float_to_int(f13)228        i14 = cast_float_to_int(f14)229        i15 = cast_float_to_int(f15)230        i16 = cast_float_to_int(f16)231        i17 = cast_float_to_int(f17)232        #233        i18 = int_signext(i10, 2)234        i19 = int_signext(i11, 2)235        i20 = int_signext(i12, 2)236        i21 = int_signext(i13, 2)237        i22 = int_signext(i14, 2)238        i23 = int_signext(i15, 2)239        i24 = int_signext(i16, 2)240        i25 = int_signext(i17, 2)241        #242        raw_store(p1, i1, i18, descr=short)243        raw_store(p1, i2, i19, descr=short)244        raw_store(p1, i3, i20, descr=short)245        raw_store(p1, i4, i21, descr=short)246        raw_store(p1, i5, i22, descr=short)247        raw_store(p1, i6, i23, descr=short)248        raw_store(p1, i7, i24, descr=short)249        raw_store(p1, i8, i25, descr=short)250        """)251        pack1 = self.pack(loop1, 0, 8)252        pack2 = self.pack(loop1, 8, 16)253        pack3 = self.pack(loop1, 16, 24)254        pack4 = self.pack(loop1, 24, 32)255        def void(b,c):256            pass257        loop2 = self.schedule(loop1, [pack1,pack2,pack3,pack4],258                              overwrite_funcs={259                                  '_prevent_signext': void260                              })261        loop3 = self.parse_trace("""262        v10[2xf64] = vec_load_f(p0, i1, 1, 0, descr=double)263        v11[2xf64] = vec_load_f(p0, i3, 1, 0, descr=double)264        v12[2xf64] = vec_load_f(p0, i5, 1, 0, descr=double)265        v13[2xf64] = vec_load_f(p0, i7, 1, 0, descr=double)266        v14[2xi32] = vec_cast_float_to_int(v10[2xf64])267        v15[2xi32] = vec_cast_float_to_int(v11[2xf64])268        v16[2xi32] = vec_cast_float_to_int(v12[2xf64])269        v17[2xi32] = vec_cast_float_to_int(v13[2xf64])270        v22[4xi32] = vec_pack_i(v14[2xi32], v15[2xi32], 2, 2)271        v18[4xi16] = vec_int_signext(v22[4xi32],2)272        v23[6xi16] = vec_pack_i(v16[2xi32], v17[2xi32], 2, 2)273        v20[4xi16] = vec_int_signext(v23[4xi32],2)274        v24[8xi16] = vec_pack_i(v18[4xi16], v20[4xi16], 4, 4)275        vec_store(p1, i1, v24[8xi16], 1, 0, descr=short)276        """, False)277        self.assert_equal(loop2, loop3)278    def test_cast_float_to_single_float(self):279        loop1 = self.parse_trace("""280        f10 = raw_load_f(p0, i1, descr=double)281        f11 = raw_load_f(p0, i2, descr=double)282        f12 = raw_load_f(p0, i3, descr=double)283        f13 = raw_load_f(p0, i4, descr=double)284        #285        i10 = cast_float_to_singlefloat(f10)286        i11 = cast_float_to_singlefloat(f11)287        i12 = cast_float_to_singlefloat(f12)288        i13 = cast_float_to_singlefloat(f13)289        #290        raw_store(p1, i1, i10, descr=float)291        raw_store(p1, i2, i11, descr=float)292        raw_store(p1, i3, i12, descr=float)293        raw_store(p1, i4, i13, descr=float)294        """)295        pack1 = self.pack(loop1, 0, 4)296        pack2 = self.pack(loop1, 4, 8)297        pack3 = self.pack(loop1, 8, 12)298        loop2 = self.schedule(loop1, [pack1,pack2,pack3])299        loop3 = self.parse_trace("""300        v44[2xf64] = vec_load_f(p0, i1, 1, 0, descr=double) 301        v45[2xf64] = vec_load_f(p0, i3, 1, 0, descr=double) 302        v46[2xi32] = vec_cast_float_to_singlefloat(v44[2xf64]) 303        v47[2xi32] = vec_cast_float_to_singlefloat(v45[2xf64]) 304        v41[4xi32] = vec_pack_i(v46[2xi32], v47[2xi32], 2, 2) 305        vec_store(p1, i1, v41[4xi32], 1, 0, descr=float)306        """, False)307        self.assert_equal(loop2, loop3)308    def test_all(self):309        loop1 = self.parse_trace("""310        i10 = raw_load_i(p0, i1, descr=long)311        i11 = raw_load_i(p0, i2, descr=long)312        #313        i12 = int_and(i10, 255)314        i13 = int_and(i11, 255)315        #316        guard_true(i12) []317        guard_true(i13) []318        """)319        pack1 = self.pack(loop1, 0, 2)320        pack2 = self.pack(loop1, 2, 4)321        pack3 = self.pack(loop1, 4, 6)322        loop2 = self.schedule(loop1, [pack1,pack2,pack3], prepend_invariant=True)323        loop3 = self.parse_trace("""324        v9[2xi64] = vec_expand_i(255)325        v10[2xi64] = vec_load_i(p0, i1, 1, 0, descr=long)326        v11[2xi64] = vec_int_and(v10[2xi64], v9[2xi64])327        vec_guard_true(v11[2xi64]) []328        """, False)329        self.assert_equal(loop2, loop3)330    def test_split_load_store(self):331        loop1 = self.parse_trace("""332        i10 = raw_load_i(p0, i1, descr=float)333        i11 = raw_load_i(p0, i2, descr=float)334        i12 = raw_load_i(p0, i3, descr=float)335        i13 = raw_load_i(p0, i4, descr=float)336        raw_store(p0, i3, i10, descr=float)337        raw_store(p0, i4, i11, descr=float)338        """)339        pack1 = self.pack(loop1, 0, 4)340        pack2 = self.pack(loop1, 4, 6)341        loop2 = self.schedule(loop1, [pack1,pack2], prepend_invariant=True)342        loop3 = self.parse_trace("""343        v1[4xi32] = vec_load_i(p0, i1, 1, 0, descr=float)344        i10 = vec_unpack_i(v1[4xi32], 0, 1)345        raw_store(p0, i3, i10, descr=float)346        i11 = vec_unpack_i(v1[4xi32], 1, 1)347        raw_store(p0, i4, i11, descr=float)348        """, False)349        # unfortunate ui32 is the type for float32... the unsigned u is for350        # the tests351        self.assert_equal(loop2, loop3)352    def test_split_arith(self):353        loop1 = self.parse_trace("""354        i10 = int_and(255, i1)355        i11 = int_and(255, i1)356        """)357        pack1 = self.pack(loop1, 0, 2)358        loop2 = self.schedule(loop1, [pack1], prepend_invariant=True)359        loop3 = self.parse_trace("""360        v1[2xi64] = vec_expand_i(255)361        v2[2xi64] = vec_expand_i(i1)362        v3[2xi64] = vec_int_and(v1[2xi64], v2[2xi64])363        """, False)364        self.assert_equal(loop2, loop3)365    def test_split_arith(self):366        loop1 = self.parse_trace("""367        i10 = int_and(255, i1)368        i11 = int_and(255, i1)369        """)370        pack1 = self.pack(loop1, 0, 2)371        loop2 = self.schedule(loop1, [pack1], prepend_invariant=True)372        loop3 = self.parse_trace("""373        v1[2xi64] = vec_expand_i(255)374        v2[2xi64] = vec_expand_i(i1)375        v3[2xi64] = vec_int_and(v1[2xi64], v2[2xi64])376        """, False)377        self.assert_equal(loop2, loop3)378    def test_no_vec_impl(self):379        loop1 = self.parse_trace("""380        i10 = int_and(255, i1)381        i11 = int_and(255, i2)382        i12 = call_pure_i(321, i10)383        i13 = call_pure_i(321, i11)384        i14 = int_and(i1, i12)385        i15 = int_and(i2, i13)386        """)387        pack1 = self.pack(loop1, 0, 2)388        pack4 = self.pack(loop1, 4, 6)389        loop2 = self.schedule(loop1, [pack1,pack4], prepend_invariant=True)390        loop3 = self.parse_trace("""391        v1[2xi64] = vec_expand_i(255)392        v2[0xi64] = vec_i()393        v3[1xi64] = vec_pack_i(v2[2xi64], i1, 0, 1)394        v4[2xi64] = vec_pack_i(v3[2xi64], i2, 1, 1)395        v5[2xi64] = vec_int_and(v1[2xi64], v4[2xi64])396        i10 = vec_unpack_i(v5[2xi64], 0, 1)397        i12 = call_pure_i(321, i10)398        i11 = vec_unpack_i(v5[2xi64], 1, 1)399        i13 = call_pure_i(321, i11)400        v6[0xi64] = vec_i()401        v7[1xi64] = vec_pack_i(v6[2xi64], i12, 0, 1)402        v8[2xi64] = vec_pack_i(v7[2xi64], i13, 1, 1)403        v9[2xi64] = vec_int_and(v4[2xi64], v8[i64])404        """, False)405        self.assert_equal(loop2, loop3)406    def test_split_cast(self):407        trace = self.parse_trace("""408        f10 = cast_int_to_float(i1)409        f11 = cast_int_to_float(i2)410        f12 = cast_int_to_float(i3)411        f13 = cast_int_to_float(i4)412        """)413        pack = self.pack(trace, 0, 4)414        packs = []415        pack.split(packs, 16, self.vector_ext)416        packs.append(pack)417        assert len(packs) == 2418    def test_combine_packset_nearly_empty_pack(self):419        trace = self.parse_trace("""420        i10 = int_add(i1, i1)421        i11 = int_add(i2, i2)422        i12 = int_add(i3, i3)423        """)424        pack = self.pack(trace, 0, 2)425        packset = FakePackSet([pack])426        packset.split_overloaded_packs(self.vector_ext)427        assert len(packset.packs) == 1428    def test_expand(self):429        state = FakeVecScheduleState()430        assert state.find_expanded([]) == None431        state.expand(['a'], 'a')432        assert state.find_expanded(['a']) == 'a'433        state.expand(['a','b','c'], 'abc')...path_parser.py
Source:path_parser.py  
1import re2from abc import ABC, abstractmethod3from typing import List, Union4from drepr.utils.validator import InputError5from ..path import Path, IndexExpr, RangeExpr, WildcardExpr, Expr6from ..resource import Resource7class PathParser(ABC):8    @abstractmethod9    def parse(self, resource: Resource, path: Union[str, list], parse_trace: str) -> Path:10        pass11    # noinspection PyMethodMayBeStatic12    def get_resource(self, resources: List[Resource], resource_id: str, trace: str) -> Resource:13        for res in resources:14            if res.id == resource_id:15                return res16        raise InputError(f"{trace}\nERROR: Refer to path of an nonexistent resource: {resource_id}")17class PathParserV1(PathParser):18    """19    A path can either be a JSONPath or our list path20    1. If the path is a JSONPath, then it is a string startswith `$`. We only support the following21       type of step: range, index, list of index, and wildcard. However, wildcard is only used for selecting22       all values of an object23    2. If the path is a normal string24    """25    REG_SRANGE = re.compile(r"^(\d+)?\.\.(-?\d+)?(?::(\d+))?$")26    REG_SINDEX = re.compile(r"^(?:\$\{([^}]+)})|(\d+)|(.*)$")27    REG_SRANGE_EXPR = re.compile(28        r"^(?:(\d+)|(?:\$\{([^}]+)}))?\.\.(?:(-\d+)|(?:\$\{([^}]+)}))?(?::(\d+)|(?:\$\{([^}]+)}))?$"29    )30    REG_JPATH_BRACKET = re.compile(r"(?:\[(-?\d+)?\:(?:(-?\d+)(?:\:(-?\d+))?)?\])|(?:\[(-?\d+)\])|(?:\['([^']+)'\])")31    REG_JPATH_DOT = re.compile(r"\.((?:(?!\.|\[).)+)")32    def parse(self, _resource: Resource, path: Union[str, list], parse_trace: str) -> Path:33        if isinstance(path, str):34            return self.parse_jsonpath(path, parse_trace)35        if isinstance(path, list):36            return self.parse_custom_path(path, parse_trace)37        raise InputError(f"{parse_trace}\nERROR: the path must either be a "38                         f"string (JSONPath) or a list of steps. Get {type(path)} instead")39    def parse_jsonpath(self, jpath: str, parse_trace: str) -> Path:40        if not jpath.startswith("$"):41            raise InputError(f"{parse_trace}\nERROR: invalid json path. The path must start with `$`. "42                             f"Get: {jpath}")43        jpath = jpath[1:]44        steps = []45        parsing_pos = 146        while len(jpath) > 0:47            if jpath.startswith("["):48                m = self.REG_JPATH_BRACKET.match(jpath)49                if m is None:50                    raise InputError(51                        f"{parse_trace}\nERROR: invalid json path, error while parsing bracket at position {parsing_pos}")52                jpath = jpath[m.span()[-1]:]53                parsing_pos += m.span()[-1]  # m.span()[0] is always 054                if m.group(5) is not None:55                    # match with string56                    steps.append(IndexExpr(m.group(5)))57                elif m.group(4) is not None:58                    # match with a single number59                    steps.append(IndexExpr(int(m.group(4))))60                else:61                    steps.append(RangeExpr(62                        int(m.group(1) or "0"),63                        int(m.group(2)) if m.group(2) is not None else None,64                        int(m.group(3) or "1")))65            elif jpath.startswith(".*~"):66                # *~ select property names67                steps.append(WildcardExpr.Names)68                jpath = jpath[3:]69                parsing_pos += 370            elif jpath.startswith(".*"):71                steps.append(WildcardExpr.Values)72                jpath = jpath[2:]73                parsing_pos += 274            else:75                m = self.REG_JPATH_DOT.match(jpath)76                if m is None:77                    raise InputError(78                        f"{parse_trace}\nERROR: invalid json path, error while parsing step at position {parsing_pos}")79                jpath = jpath[m.span()[-1]:]80                parsing_pos += m.span()[-1]  # m.span()[0] is always 081                # after a dot, it can either be a number or a string82                if m.group(1).isdigit():83                    steps.append(IndexExpr(int(m.group(1))))84                else:85                    steps.append(IndexExpr(m.group(1)))86        return Path(steps)87    def parse_custom_path(self, path: List[str], parse_trace: str) -> Path:88        steps = []89        for i, step in enumerate(path):90            trace = f"Parsing step {i} ({step})"91            if isinstance(step, str):92                m = self.REG_SRANGE.match(step)93                if m is not None:94                    steps.append(RangeExpr(95                        int(m.group(1) or '0'),96                        int(m.group(2)) if m.group(2) is not None else None,97                        int(m.group(3) or '1')))98                    continue99                m = self.REG_SRANGE_EXPR.match(step)100                if m is not None:101                    steps.append(RangeExpr(102                        (Expr(m.group(1)[2:-1]) if m.group(1).startswith("${") else int(m.group(1)))103                        if m.group(1) is not None else 0,104                        (Expr(m.group(2)[2:-1]) if m.group(2).startswith("${") else int(m.group(2)))105                        if m.group(2) is not None else None,106                        (Expr(m.group(2)[2:-1]) if m.group(2).startswith("${") else int(m.group(2)))107                        if m.group(2) is not None else 1))108                    continue109                if step.startswith("${"):110                    steps.append(IndexExpr(Expr(step[2:-1])))111                else:112                    steps.append(IndexExpr(step))113            elif isinstance(step, int):114                steps.append(IndexExpr(step))115            else:116                raise InputError(117                    f"{parse_trace}\n{trace}\nERROR: step must either be string or number. Get {type(step)} instead")...test_parse_trace.py
Source:test_parse_trace.py  
...77        line = parse_trace.Line(*line_data)78        line.git_filename = "file"79        self.assertEqual(line_data, line.traceback_format())80class TestParseTrace(base.TestCase):81    def test_parse_trace(self):82        for filename in glob.glob('git_stacktrace/tests/examples/*.trace'):83            with open(filename) as f:84                try:85                    parse_trace.parse_trace(f.readlines())86                except Exception:...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
