How to use scope_manager method in Slash

Best Python code snippet using slash

test_interpreter.py

Source:test_interpreter.py Github

copy

Full Screen

1import io2import pytest3from src.lexer.lexer import Lexer4from src.parser.parser import Parser5from src.interpreter.interpreter import Interpreter6from src.source.source import FileSource7from src.exceptions.exceptions import *8from src.interpreter.variables import *9def new_interpreter(source_string):10 source = FileSource(io.StringIO(source_string))11 lexer = Lexer(source)12 parser = Parser(lexer)13 return Interpreter(parser)14def test_program():15 interpreter = new_interpreter('main() {return;}')16 returned = interpreter.interpret()17 assert returned == 018def test_program_no_return():19 interpreter = new_interpreter('not_main() {return;}')20 with pytest.raises(NoMainFunctionException):21 interpreter.interpret()22def test_program_return_number():23 interpreter = new_interpreter('main() {return 5;}')24 returned = interpreter.interpret()25 assert returned == 526def test_program_return_negative_number():27 interpreter = new_interpreter('main() {return -5;}')28 returned = interpreter.interpret()29 assert returned == -530def test_program_return_expression():31 interpreter = new_interpreter('main() {return 1+3;}')32 returned = interpreter.interpret()33 assert returned == 434def test_program_return_expression_in_parenthesis():35 interpreter = new_interpreter('main() {return (1+3);}')36 returned = interpreter.interpret()37 assert returned == 438def test_program_return_negative_expression_in_parenthesis():39 interpreter = new_interpreter('main() {return -(1+3);}')40 returned = interpreter.interpret()41 assert returned == -442def test_program_return_subtraction_expression_in_parenthesis():43 interpreter = new_interpreter('main() {return (-1+3);}')44 returned = interpreter.interpret()45 assert returned == 246def test_program_return_condition():47 interpreter = new_interpreter('main() {return 5*(1+3);}')48 returned = interpreter.interpret()49 assert returned == 2050def test_program_with_assignment():51 interpreter = new_interpreter('main() {'52 ' a = 7;'53 ' return a;'54 '}'55 )56 returned = interpreter.interpret()57 assert returned == 758def test_program_with_init_number_assignment():59 interpreter = new_interpreter('main() {'60 ' a = number(7);'61 ' return a;'62 '}'63 )64 returned = interpreter.interpret()65 assert returned == 766def test_program_with_init_number_assignment_by_variable():67 interpreter = new_interpreter('main() {'68 ' n = 7;'69 ' a = number(n);'70 ' return a;'71 '}'72 )73 returned = interpreter.interpret()74 assert returned == 775def test_program_with_init_number_assignment_zero():76 interpreter = new_interpreter('main() {'77 ' a = number();'78 ' return a;'79 '}'80 )81 returned = interpreter.interpret()82 assert returned == 083def test_program_with_init_pixel_assignment():84 interpreter = new_interpreter('main() {'85 ' a = pixel(5, 10, 15);'86 ' return a;'87 '}'88 )89 returned = interpreter.interpret()90 assert returned == 091 assert interpreter.scope_manager.last_result == PixelVariable('a', 5, 10, 15)92def test_program_with_init_pixel_assignment_over_limit():93 interpreter = new_interpreter('main() {'94 ' a = pixel(5, 10, 1005);'95 ' return a;'96 '}'97 )98 returned = interpreter.interpret()99 assert returned == 0100 assert interpreter.scope_manager.last_result == PixelVariable('a', 5, 10, 255)101def test_program_with_init_pixel_assignment_below_limit():102 interpreter = new_interpreter('main() {'103 ' a = pixel(5, 10, -2);'104 ' return a;'105 '}'106 )107 returned = interpreter.interpret()108 assert returned == 0109 assert interpreter.scope_manager.last_result == PixelVariable('a', 5, 10, 0)110def test_program_with_init_pixel_assignment_by_variables():111 interpreter = new_interpreter('main() {'112 ' r = 5;'113 ' g = 10;'114 ' b = 15;'115 ' a = pixel(r, g, b);'116 ' return a;'117 '}'118 )119 returned = interpreter.interpret()120 assert returned == 0121 assert interpreter.scope_manager.last_result == PixelVariable('a', 5, 10, 15)122def test_program_with_init_pixel_assignment_zeros():123 interpreter = new_interpreter('main() {'124 ' a = pixel();'125 ' return a;'126 '}'127 )128 returned = interpreter.interpret()129 assert returned == 0130 assert interpreter.scope_manager.last_result == PixelVariable('a', 0, 0, 0)131def test_program_with_init_pixel_assignment_same_value():132 interpreter = new_interpreter('main() {'133 ' a = pixel(77);'134 ' return a;'135 '}'136 )137 returned = interpreter.interpret()138 assert returned == 0139 assert interpreter.scope_manager.last_result == PixelVariable('a', 77, 77, 77)140def test_program_with_init_matrix_assignment_zeros():141 interpreter = new_interpreter('main() {'142 ' a = matrix(3);'143 ' return a;'144 '}'145 )146 returned = interpreter.interpret()147 assert returned == 0148 assert interpreter.scope_manager.last_result == MatrixVariable('a', [[0, 0, 0]])149def test_program_with_init_matrix_assignment_zeros2d():150 interpreter = new_interpreter('main() {'151 ' a = matrix(3,2);'152 ' return a;'153 '}'154 )155 returned = interpreter.interpret()156 assert returned == 0157 assert interpreter.scope_manager.last_result == MatrixVariable('a', [[0, 0],158 [0, 0],159 [0, 0]])160def test_program_with_init_matrix_assignment_zeros3d():161 interpreter = new_interpreter('main() {'162 ' a = matrix(2,3,2);'163 ' return a;'164 '}'165 )166 returned = interpreter.interpret()167 assert returned == 0168 assert interpreter.scope_manager.last_result == Matrix3dVariable('a', [169 MatrixVariable('', [[0, 0],170 [0, 0],171 [0, 0]]),172 MatrixVariable('', [[0, 0],173 [0, 0],174 [0, 0]])175 ])176def test_program_return_variable_expression():177 interpreter = new_interpreter('main() {'178 ' a = 7;'179 ' b = 5;'180 ' return a+b;'181 '}'182 )183 returned = interpreter.interpret()184 assert returned == 12185def test_program_conditional_return():186 interpreter = new_interpreter('main() {'187 ' a = 6;'188 ' if (2>1)'189 ' a = 2;'190 ' else'191 ' a = 5;'192 ' return a;'193 '}'194 )195 returned = interpreter.interpret()196 assert returned == 2197def test_program_conditional_return_else():198 interpreter = new_interpreter('main() {'199 ' a = 6;'200 ' if (2<1)'201 ' a = 2;'202 ' else'203 ' a = 5;'204 ' return a;'205 '}'206 )207 returned = interpreter.interpret()208 assert returned == 5209def test_program_direct_conditional_return():210 interpreter = new_interpreter('main() {'211 ' if (2>1)'212 ' return 2;'213 ' else'214 ' return 5;'215 ' return;'216 '}'217 )218 returned = interpreter.interpret()219 assert returned == 2220def test_program_direct_conditional_return_else():221 interpreter = new_interpreter('main() {'222 ' if (2<1)'223 ' return 2;'224 ' else'225 ' return 5;'226 ' return;'227 '}'228 )229 returned = interpreter.interpret()230 assert returned == 5231def test_program_number_as_condition():232 interpreter = new_interpreter('main() {'233 ' if (2)'234 ' return 2;'235 ' else'236 ' return 5;'237 ' return;'238 '}'239 )240 returned = interpreter.interpret()241 assert returned == 2242def test_program_number_as_condition_zero():243 interpreter = new_interpreter('main() {'244 ' if (0)'245 ' return 2;'246 ' else'247 ' return 5;'248 ' return;'249 '}'250 )251 returned = interpreter.interpret()252 assert returned == 5253def test_program_number_as_condition_negation():254 interpreter = new_interpreter('main() {'255 ' if (!(2<1))'256 ' return 2;'257 ' else'258 ' return 5;'259 ' return;'260 '}'261 )262 returned = interpreter.interpret()263 assert returned == 2264def test_program_for_loop():265 interpreter = new_interpreter('main() {'266 ' a = 0;'267 ' for (i in 5) {'268 ' a = a+1;'269 ' }'270 ' return a;'271 '}'272 )273 returned = interpreter.interpret()274 assert returned == 5275def test_program_while_loop():276 interpreter = new_interpreter('main() {'277 ' a = 0;'278 ' while (a < 5) {'279 ' a = a+1;'280 ' }'281 ' return a;'282 '}'283 )284 returned = interpreter.interpret()285 assert returned == 5286def test_program_with_new_operator():287 interpreter = new_interpreter('newop( avg, n1 of number, n2 of number) {'288 ' return (n1 + n2) / 2;'289 '}'290 'main() {'291 ' a = 4;'292 ' b = 2;'293 ' return a avg b;'294 '}'295 )296 returned = interpreter.interpret()297 assert returned == 3298def test_program_with_new_operator_after_main():299 interpreter = new_interpreter('main() {'300 ' a = 4;'301 ' b = 2;'302 ' return a avg b;'303 '}'304 'newop( avg, n1 of number, n2 of number) {'305 ' return (n1 + n2) / 2;'306 '}'307 )308 returned = interpreter.interpret()309 assert returned == 3310def test_program_matrix_lookup():311 interpreter = new_interpreter('main() {'312 ' m = matrix(3,2);'313 ' a = m[2,1];'314 ' return a;'315 '}'316 )317 returned = interpreter.interpret()318 assert returned == 0319def test_program_assign_by_matrix_lookup():320 interpreter = new_interpreter('main() {'321 ' m = matrix(3,2);'322 ' m[0,0] = 2;'323 ' return;'324 '}'325 )326 returned = interpreter.interpret()327 assert returned == 0328 assert interpreter.scope_manager.last_result == MatrixVariable('m', [[2, 0],329 [0, 0],330 [0, 0]])331def test_program_assign_matrix_literal():332 interpreter = new_interpreter('main() {'333 ' m = [1, 2, 3;];'334 ' return;'335 '}'336 )337 returned = interpreter.interpret()338 assert returned == 0339 assert interpreter.scope_manager.last_result == MatrixVariable('m', [[1, 2, 3]])340def test_program_assign_matrix_literal_3d():341 interpreter = new_interpreter('main() {'342 ' a = {'343 ' [1, 2;'344 ' 3, 4;'345 ' 5, 6;],'346 ''347 ' [7, 8;'348 ' 9, 10;'349 ' 11, 12;]'350 ' };'351 ' return a;'352 '}'353 )354 returned = interpreter.interpret()355 assert returned == 0356 assert interpreter.scope_manager.last_result == Matrix3dVariable('a', [357 MatrixVariable('', [[1, 2],358 [3, 4],359 [5, 6]]),360 MatrixVariable('', [[7, 8],361 [9, 10],362 [11, 12]])363 ])364def test_program_get_pixel_r():365 interpreter = new_interpreter('main() {'366 ' p = pixel(100, 200, 50);'367 ' red = p.r;'368 ''369 ' return red;'370 '}'371 )372 returned = interpreter.interpret()373 assert returned == 100374def test_program_set_pixel_r():375 interpreter = new_interpreter('main() {'376 ' p = pixel(100, 200, 50);'377 ' p.r = 15;'378 ''379 ' return p;'380 '}'381 )382 returned = interpreter.interpret()383 assert returned == 0384 assert interpreter.scope_manager.last_result == PixelVariable('p', 15, 200, 50)385def test_program_set_pixel_b_over_limit():386 interpreter = new_interpreter('main() {'387 ' p = pixel(100, 200, 50);'388 ' p.b = 1500;'389 ''390 ' return p;'391 '}'392 )393 returned = interpreter.interpret()394 assert returned == 0395 assert interpreter.scope_manager.last_result == PixelVariable('p', 100, 200, 255)396def test_program_get_matrix_dims():397 interpreter = new_interpreter('main() {'398 ' m = matrix(3,2);'399 ' return m.dims;'400 '}'401 )402 returned = interpreter.interpret()403 assert returned == 2404def test_program_get_matrix_xdim():405 interpreter = new_interpreter('main() {'406 ' m = matrix(3,2);'407 ' return m.xdim;'408 '}'409 )410 returned = interpreter.interpret()411 assert returned == 2412def test_program_get_matrix_ydim():413 interpreter = new_interpreter('main() {'414 ' m = matrix(3,2);'415 ' return m.ydim;'416 '}'417 )418 returned = interpreter.interpret()419 assert returned == 3420def test_program_get_matrix_zdim():421 interpreter = new_interpreter('main() {'422 ' m = matrix(5,2,7);'423 ' return m.zdim;'424 '}'425 )426 returned = interpreter.interpret()427 assert returned == 5428def test_program_exception_get_matrix_wdim():429 interpreter = new_interpreter('main() {'430 ' m = matrix(5,2,7);'431 ' return m.wdim;'432 '}'433 )434 with pytest.raises(UndefinedReferenceException):435 interpreter.interpret()436def test_program_with_function_call():437 interpreter = new_interpreter('foo() { return 5;}'438 'main() {'439 ' m = foo();'440 ' return m;'441 '}'442 )443 returned = interpreter.interpret()444 assert returned == 5445def test_program_with_function_call_negative():446 interpreter = new_interpreter('foo() { return 5;}'447 'main() {'448 ' m = -foo();'449 ' return m;'450 '}'451 )452 returned = interpreter.interpret()453 assert returned == -5454def test_program_with_function_call_with_arguments():455 interpreter = new_interpreter('foo(a, b) { return a*b;}'456 'main() {'457 ' m = foo(3, 4);'458 ' return m;'459 '}'460 )461 returned = interpreter.interpret()462 assert returned == 12463def test_program_with_function_call_with_expressions_arguments():464 interpreter = new_interpreter('foo(a, b) { return a*b;}'465 'main() {'466 ' m = foo(foo(3,2), 1+1);'467 ' return m;'468 '}'469 )470 returned = interpreter.interpret()471 assert returned == 12472def test_program_with_function_call_with_expressions_arguments_multiplication():473 interpreter = new_interpreter('foo(a, b) { return a*b;}'474 'main() {'475 ' m = foo(foo(3,2), 1+2*3);'476 ' return m;'477 '}'478 )479 returned = interpreter.interpret()480 assert returned == 42481def test_program_with_function_call_with_expression3():482 interpreter = new_interpreter('foo(a, b) { return a*b;}'483 'main() {'484 ' m = foo(foo(3,2), 1+2*3-4);'485 ' return m;'486 '}'487 )488 returned = interpreter.interpret()489 assert returned == 18490def test_program_with_function_call_expression():491 interpreter = new_interpreter('foo() { return 5;}'492 'main() {'493 ' m = foo() + 3;'494 ' return m;'495 '}'496 )497 returned = interpreter.interpret()498 assert returned == 8499def test_program_with_recursive_function_call():500 interpreter = new_interpreter('foo(a) { '501 ' if (a == 1) return 1;'502 ' return foo(a-1) + 1;'503 '}'504 ''505 'main() {'506 ' m = foo(3);'507 ' return m;'508 '}'509 )510 returned = interpreter.interpret()511 assert returned == 3512def test_program_addition():513 interpreter = new_interpreter(514 'main() {'515 ' a = 5;'516 ' b = 9;'517 ' c = a + b;'518 ' return c;'519 '}'520 )521 returned = interpreter.interpret()522 assert returned == 14523def test_program_subtraction():524 interpreter = new_interpreter(525 'main() {'526 ' a = 5;'527 ' b = 9;'528 ' c = a - b;'529 ' return c;'530 '}'531 )532 returned = interpreter.interpret()533 assert returned == -4534def test_program_multiplication():535 interpreter = new_interpreter(536 'main() {'537 ' a = 5;'538 ' b = 9;'539 ' c = a * b;'540 ' return c;'541 '}'542 )543 returned = interpreter.interpret()544 assert returned == 45545def test_program_division():546 interpreter = new_interpreter(547 'main() {'548 ' a = 5;'549 ' b = 9;'550 ' c = a / b;'551 ' return c;'552 '}'553 )554 returned = interpreter.interpret()555 assert returned == 0556def test_program_division_by_zero():557 interpreter = new_interpreter(558 'main() {'559 ' a = 5;'560 ' b = 0;'561 ' c = a / b;'562 ' return c;'563 '}'564 )565 with pytest.raises(ZeroDivisionException):566 interpreter.interpret()567def test_program_whole_division():568 interpreter = new_interpreter(569 'main() {'570 ' a = 45;'571 ' b = 9;'572 ' c = a / b;'573 ' return c;'574 '}'575 )576 returned = interpreter.interpret()577 assert returned == 5578def test_program_modulo():579 interpreter = new_interpreter(580 'main() {'581 ' a = 5;'582 ' b = 9;'583 ' c = a % b;'584 ' return c;'585 '}'586 )587 returned = interpreter.interpret()588 assert returned == 5589def test_program_expression():590 interpreter = new_interpreter(591 'main() {'592 ' a = 5;'593 ' b = 9;'594 ' c = 1;'595 ' return a * b + c;'596 '}'597 )598 returned = interpreter.interpret()599 assert returned == 46600def test_program_addition_pixel():601 interpreter = new_interpreter(602 'main() {'603 ' a = pixel(1, 2, 3);'604 ' b = pixel(2, 2, 2);'605 ' c = a + b;'606 ' return c;'607 '}'608 )609 returned = interpreter.interpret()610 assert returned == 0611 assert interpreter.scope_manager.last_result == PixelVariable('c', 3, 4, 5)612def test_program_subtraction_pixel():613 interpreter = new_interpreter(614 'main() {'615 ' a = pixel(1, 2, 3);'616 ' b = pixel(2, 2, 2);'617 ' c = a - b;'618 ' return c;'619 '}'620 )621 returned = interpreter.interpret()622 assert returned == 0623 assert interpreter.scope_manager.last_result == PixelVariable('c', 0, 0, 1)624def test_program_multiplication_pixel():625 interpreter = new_interpreter(626 'main() {'627 ' a = pixel(1, 2, 3);'628 ' b = pixel(2, 2, 3);'629 ' c = a * b;'630 ' return c;'631 '}'632 )633 returned = interpreter.interpret()634 assert returned == 0635 assert interpreter.scope_manager.last_result == PixelVariable('c', 2, 4, 9)636def test_program_multiplication_pixel_by_number():637 interpreter = new_interpreter(638 'main() {'639 ' a = pixel(1, 2, 3);'640 ' b = 2;'641 ' c = a * b;'642 ' return c;'643 '}'644 )645 returned = interpreter.interpret()646 assert returned == 0647 assert interpreter.scope_manager.last_result == PixelVariable('c', 2, 4, 6)648def test_program_multiplication_pixel_by_number_reversed():649 interpreter = new_interpreter(650 'main() {'651 ' a = pixel(1, 2, 3);'652 ' b = 2;'653 ' c = b * a;'654 ' return c;'655 '}'656 )657 returned = interpreter.interpret()658 assert returned == 0659 assert interpreter.scope_manager.last_result == PixelVariable('c', 2, 4, 6)660def test_program_addition_pixel_number():661 interpreter = new_interpreter(662 'main() {'663 ' a = pixel(1, 2, 3);'664 ' b = 2;'665 ' c = a + b;'666 ' return c;'667 '}'668 )669 returned = interpreter.interpret()670 assert returned == 0671 assert interpreter.scope_manager.last_result == PixelVariable('c', 3, 4, 5)672def test_program_matrix_addition():673 interpreter = new_interpreter(674 'main() {'675 ' a = [1, 2;'676 ' 1, 2;];'677 ' b = [3, 2;'678 ' 1, 1;];'679 ' c = a + b;'680 ' return c;'681 '}'682 )683 returned = interpreter.interpret()684 assert returned == 0685 assert interpreter.scope_manager.last_result == MatrixVariable('c', [[4, 4],686 [2, 3]])687def test_program_matrix_subtraction():688 interpreter = new_interpreter(689 'main() {'690 ' a = [1, 2;'691 ' 1, 2;];'692 ' b = [3, 2;'693 ' 1, 1;];'694 ' c = a - b;'695 ' return c;'696 '}'697 )698 returned = interpreter.interpret()699 assert returned == 0700 assert interpreter.scope_manager.last_result == MatrixVariable('c', [[-2, 0],701 [0, 1]])702def test_program_matrix_special_multiplication():703 interpreter = new_interpreter(704 'main() {'705 ' a = [1, 2;'706 ' 1, 2;'707 ' 3, 3;];'708 ' b = [3, 2;'709 ' 1, 1;'710 ' 2, 1;];'711 ' c = a @ b;'712 ' return c;'713 '}'714 )715 returned = interpreter.interpret()716 assert returned == 0717 assert interpreter.scope_manager.last_result == MatrixVariable('c', [[3, 4],718 [1, 2],719 [6, 3]])720def test_program_matrix_multiplication():721 interpreter = new_interpreter(722 'main() {'723 ' a = [1, 2;'724 ' 1, 2;'725 ' 3, 3;];'726 ' b = [3, 2, 1;'727 ' 1, 1, 3;];'728 ' c = a * b;'729 ' return c;'730 '}'731 )732 returned = interpreter.interpret()733 assert returned == 0734 assert interpreter.scope_manager.last_result == MatrixVariable('c', [[5, 4, 7],735 [5, 4, 7],736 [12, 9, 12]])737def test_program_matrix_addition_number():738 interpreter = new_interpreter(739 'main() {'740 ' a = [1, 2;'741 ' 1, 3;];'742 ' b = 2;'743 ' c = a + b;'744 ' return c;'745 '}'746 )747 returned = interpreter.interpret()748 assert returned == 0749 assert interpreter.scope_manager.last_result == MatrixVariable('c', [[3, 4],750 [3, 5]])751def test_program_matrix_subtraction_number():752 interpreter = new_interpreter(753 'main() {'754 ' a = [1, 2;'755 ' 1, 3;];'756 ' b = 2;'757 ' c = a - b;'758 ' return c;'759 '}'760 )761 returned = interpreter.interpret()762 assert returned == 0763 assert interpreter.scope_manager.last_result == MatrixVariable('c', [[-1, 0],764 [-1, 1]])765def test_program_matrix_multiplication_number():766 interpreter = new_interpreter(767 'main() {'768 ' a = [1, 2;'769 ' 1, 3;];'770 ' b = 2;'771 ' c = a * b;'772 ' return c;'773 '}'774 )775 returned = interpreter.interpret()776 assert returned == 0777 assert interpreter.scope_manager.last_result == MatrixVariable('c', [[2, 4],778 [2, 6]])779def test_greater_than_condition_positive():780 interpreter = new_interpreter('a > b')781 condition = interpreter.parser.parse_condition()782 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 10))783 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))784 interpreter.visit_condition(condition)785 assert interpreter.scope_manager.last_result is True786def test_greater_than_condition_negative():787 interpreter = new_interpreter('a > b')788 condition = interpreter.parser.parse_condition()789 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 2))790 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))791 interpreter.visit_condition(condition)792 assert interpreter.scope_manager.last_result is False793def test_less_than_condition_positive():794 interpreter = new_interpreter('a < b')795 condition = interpreter.parser.parse_condition()796 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 1))797 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))798 interpreter.visit_condition(condition)799 assert interpreter.scope_manager.last_result is True800def test_less_than_condition_negative():801 interpreter = new_interpreter('a < b')802 condition = interpreter.parser.parse_condition()803 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 23))804 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))805 interpreter.visit_condition(condition)806 assert interpreter.scope_manager.last_result is False807def test_greater_than_or_equal_condition_positive():808 interpreter = new_interpreter('a >= b')809 condition = interpreter.parser.parse_condition()810 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 10))811 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))812 interpreter.visit_condition(condition)813 assert interpreter.scope_manager.last_result is True814def test_greater_than_or_equal_condition_equal():815 interpreter = new_interpreter('a >= b')816 condition = interpreter.parser.parse_condition()817 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 10))818 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 10))819 interpreter.visit_condition(condition)820 assert interpreter.scope_manager.last_result is True821def test_greater_than_or_equal_condition_negative():822 interpreter = new_interpreter('a >= b')823 condition = interpreter.parser.parse_condition()824 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 2))825 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))826 interpreter.visit_condition(condition)827 assert interpreter.scope_manager.last_result is False828def test_less_than_or_equal_condition_positive():829 interpreter = new_interpreter('a <= b')830 condition = interpreter.parser.parse_condition()831 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 6))832 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 10))833 interpreter.visit_condition(condition)834 assert interpreter.scope_manager.last_result is True835def test_less_than_or_equal_condition_equal():836 interpreter = new_interpreter('a <= b')837 condition = interpreter.parser.parse_condition()838 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 10))839 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 10))840 interpreter.visit_condition(condition)841 assert interpreter.scope_manager.last_result is True842def test_less_than_or_equal_condition_negative():843 interpreter = new_interpreter('a <= b')844 condition = interpreter.parser.parse_condition()845 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 7))846 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))847 interpreter.visit_condition(condition)848 assert interpreter.scope_manager.last_result is False849def test_equals_condition_positive():850 interpreter = new_interpreter('a == b')851 condition = interpreter.parser.parse_condition()852 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 6))853 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 6))854 interpreter.visit_condition(condition)855 assert interpreter.scope_manager.last_result is True856def test_equals_condition_negative():857 interpreter = new_interpreter('a == b')858 condition = interpreter.parser.parse_condition()859 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 23))860 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))861 interpreter.visit_condition(condition)862 assert interpreter.scope_manager.last_result is False863def test_not_equals_condition_positive():864 interpreter = new_interpreter('a != b')865 condition = interpreter.parser.parse_condition()866 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 7))867 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 6))868 interpreter.visit_condition(condition)869 assert interpreter.scope_manager.last_result is True870def test_not_equals_condition_negative():871 interpreter = new_interpreter('a != b')872 condition = interpreter.parser.parse_condition()873 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 5))874 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))875 interpreter.visit_condition(condition)876 assert interpreter.scope_manager.last_result is False877def test_equals_and_condition():878 interpreter = new_interpreter('a == b and 1 == 1')879 condition = interpreter.parser.parse_condition()880 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 5))881 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))882 interpreter.visit_condition(condition)883 assert interpreter.scope_manager.last_result is True884def test_equals_and_condition_negative_left():885 interpreter = new_interpreter('a == b and 1 == 1')886 condition = interpreter.parser.parse_condition()887 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 5))888 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 6))889 interpreter.visit_condition(condition)890 assert interpreter.scope_manager.last_result is False891def test_equals_and_condition_negative_right():892 interpreter = new_interpreter('a == b and 1 == 2')893 condition = interpreter.parser.parse_condition()894 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 5))895 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))896 interpreter.visit_condition(condition)897 assert interpreter.scope_manager.last_result is False898def test_equals_and_condition_negative():899 interpreter = new_interpreter('a == b and 1 == 2')900 condition = interpreter.parser.parse_condition()901 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 5))902 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 4))903 interpreter.visit_condition(condition)904 assert interpreter.scope_manager.last_result is False905def test_equals_or_condition_both_true():906 interpreter = new_interpreter('a == b or 1 == 1')907 condition = interpreter.parser.parse_condition()908 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 5))909 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))910 interpreter.visit_condition(condition)911 assert interpreter.scope_manager.last_result is True912def test_equals_or_condition_left_true():913 interpreter = new_interpreter('a == b or 1 == 2')914 condition = interpreter.parser.parse_condition()915 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 5))916 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))917 interpreter.visit_condition(condition)918 assert interpreter.scope_manager.last_result is True919def test_equals_or_condition_right_true():920 interpreter = new_interpreter('a != b or 1 == 1')921 condition = interpreter.parser.parse_condition()922 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 5))923 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))924 interpreter.visit_condition(condition)925 assert interpreter.scope_manager.last_result is True926def test_equals_or_condition_both_false():927 interpreter = new_interpreter('a != b or 1 != 1')928 condition = interpreter.parser.parse_condition()929 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 5))930 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))931 interpreter.visit_condition(condition)932 assert interpreter.scope_manager.last_result is False933def test_equals_or_condition_both_false_with_negation():934 interpreter = new_interpreter('a != b or !(2 < 1)')935 condition = interpreter.parser.parse_condition()936 interpreter.scope_manager.add_update_variable('a', NumberVariable('a', 5))937 interpreter.scope_manager.add_update_variable('b', NumberVariable('b', 5))938 interpreter.visit_condition(condition)939 assert interpreter.scope_manager.last_result is True940def test_program_builtin_print():941 interpreter = new_interpreter('main() {'942 ' a = 5;'943 ' print(a);'944 ' return;'945 '}'946 )947 interpreter.interpret()948def test_program_builtin_random_pixel():949 interpreter = new_interpreter('main() {'950 ' p = random_pixel();'951 ' return;'952 '}'953 )954 interpreter.interpret()955 assert isinstance(interpreter.scope_manager.last_result, PixelVariable)956def test_program_builtin_det_2by2():957 interpreter = new_interpreter('main() {'958 ' m = [1, 2;'959 ' 3, 4;];'960 ' d = det(m);'961 ' return d;'962 '}'963 )964 returned = interpreter.interpret()965 assert returned == -2966def test_program_builtin_det_3by3():967 interpreter = new_interpreter('main() {'968 ' m = [1, 2, 3;'969 ' 2, 3, 1;'970 ' 1, 1, 3;];'971 ' d = det(m);'972 ' return d;'973 '}'974 )975 returned = interpreter.interpret()976 assert returned == -5977def test_return_from_if():978 interpreter = new_interpreter('main() {'979 ' return foo();'980 '}'981 ''982 'foo() {'983 ' if (2 < 1) {'984 ' return 3;'985 ' } else {'986 ' if (2<1){'987 ' return 2;'988 ' } else {'989 ' return 1;'990 ' }'991 ' }'992 '}'993 )994 returned = interpreter.interpret()995 assert returned == 1996def test_return_from_while():997 interpreter = new_interpreter('main() {'998 ' return foo(3);'999 '}'1000 ''1001 'foo(a) {'1002 ' while (a<2) {'1003 ' return a;'1004 ' }'1005 ' return 5;'1006 '}'1007 )1008 returned = interpreter.interpret()1009 assert returned == 51010def test_return_from_for():1011 interpreter = new_interpreter('main() {'1012 ' return foo(0);'1013 '}'1014 ''1015 'foo(a) {'1016 ' i = 0;'1017 ' for (g in 3) {'1018 ' a = a + 1;'1019 ' return a;'1020 ' }'1021 ' return 10;'1022 '}'1023 )1024 returned = interpreter.interpret()...

Full Screen

Full Screen

interpreter.py

Source:interpreter.py Github

copy

Full Screen

1from .scope import ScopeManager2from .visitor import Visitor3from .variables import *4from .builtin_functions import *5from ..lexer.token_type import TokenType6from ..parser.syntax import *7from ..exceptions.exceptions import *8class Interpreter(Visitor):9 def __init__(self, parser):10 self.parser = parser11 self.scope_manager = ScopeManager()12 def interpret(self):13 self.__load_built_in_functions()14 try:15 self.parser.parse_program()16 self.parser.program.accept(self)17 except Exception as exc:18 print("\n{}".format(exc))19 return -120 return self.__return_result()21 22 def visit_program(self, program: Program):23 main_function = None24 for function_definition in program.function_definitions:25 self.scope_manager.add_function(function_definition.id, function_definition)26 if function_definition.id == 'main':27 main_function = function_definition28 for operator_definition in program.operator_definitions:29 self.scope_manager.add_function(operator_definition.id, operator_definition)30 if main_function is None:31 raise NoMainFunctionException()32 main_function.block.accept(self)33 def visit_block(self, block: Block):34 for statement in block.statements:35 statement.accept(self)36 if self.scope_manager.return_result is not None:37 return38 def visit_if_statement(self, if_statement: IfStatement):39 if_statement.condition.accept(self)40 if self.scope_manager.last_result:41 if_statement.block.accept(self)42 elif if_statement.else_block is not None:43 if_statement.else_block.accept(self)44 def visit_while_loop(self, while_loop: WhileLoop):45 while while_loop.condition.accept(self) and self.scope_manager.last_result is True:46 while_loop.block.accept(self)47 if self.scope_manager.return_result is not None:48 return49 def visit_for_loop(self, for_loop: ForLoop):50 for_iterator = 051 for_loop.expression.accept(self)52 if not isinstance(self.scope_manager.last_result, NumberVariable):53 raise ArgumentTypeException(self.scope_manager.last_result.name,54 'number', type(self.scope_manager.last_result))55 iterator_variable = self.scope_manager.last_result56 iterator_variable.name = for_loop.iterator57 for_limit = self.scope_manager.last_result.value58 while for_iterator < for_limit:59 iterator_variable.value = for_iterator60 self.scope_manager.add_update_variable(for_loop.iterator, iterator_variable)61 for_loop.block.accept(self)62 if self.scope_manager.return_result is not None:63 return64 for_iterator += 165 def visit_function_call(self, function_call: FunctionCall):66 name = function_call.id67 function = self.scope_manager.get_function(name)68 function_call.argument_list.accept(self)69 arguments = self.scope_manager.last_result70 self.__execute_function(function, arguments)71 def visit_function_definition(self, function_definition: FunctionDefinition):72 function_definition.block.accept(self)73 def visit_argument_list(self, argument_list: ArgumentList):74 arguments = []75 for expression in argument_list.expressions:76 expression.accept(self)77 arguments.append(self.scope_manager.last_result)78 self.scope_manager.last_result = arguments79 def visit_matrix(self, matrix: Matrix):80 rows = []81 for m_row in matrix.rows:82 m_row.accept(self)83 row = []84 for variable in self.scope_manager.last_result:85 row.append(variable.value)86 rows.append(row)87 self.scope_manager.last_result = MatrixVariable('', rows)88 def visit_matrix3d(self, matrix3d: Matrix3d):89 matrices = []90 for matrix in matrix3d.matrices:91 matrix.accept(self)92 matrices.append(self.scope_manager.last_result)93 self.scope_manager.last_result = Matrix3dVariable('', matrices)94 def visit_expression_in_parenthesis(self, expression_in_parenthesis: ExpressionInParenthesis):95 expression_in_parenthesis.expression.accept(self)96 def visit_base_expression(self, base_expression: BaseExpression):97 if base_expression.subtract_operator:98 sign = -199 else:100 sign = 1101 if isinstance(base_expression.expression, int):102 self.scope_manager.last_result = NumberVariable('', sign * base_expression.expression)103 elif isinstance(base_expression.expression, str):104 variable = self.scope_manager.get_variable(base_expression.expression)105 self.scope_manager.last_result = deepcopy(variable)106 elif isinstance(base_expression.expression, Matrix) or\107 isinstance(base_expression.expression, Matrix3d) or\108 isinstance(base_expression.expression, InitStatement) or\109 isinstance(base_expression.expression, Reference) or\110 isinstance(base_expression.expression, MatrixLookup) or\111 isinstance(base_expression.expression, FunctionCall) or\112 isinstance(base_expression.expression, ExpressionInParenthesis):113 base_expression.expression.accept(self)114 self.scope_manager.last_result *= NumberVariable('', sign)115 def visit_multiplicative_expression(self, multiplicative_expression: MultiplicativeExpression):116 multiplicative_expression.base_expressions[0].accept(self)117 result = self.scope_manager.last_result118 for operator, expression in zip(multiplicative_expression.multiplicative_operators,119 multiplicative_expression.base_expressions[1:]):120 expression.accept(self)121 if operator == TokenType.MULTIPLY:122 result *= self.scope_manager.last_result123 elif operator == TokenType.DIVIDE:124 if self.scope_manager.last_result.has_zero():125 raise ZeroDivisionException()126 result /= self.scope_manager.last_result127 elif operator == TokenType.MODULO:128 result %= self.scope_manager.last_result129 elif operator == TokenType.SPECIAL_MULTIPLY:130 if not isinstance(result, MatrixVariable) or isinstance(result, Matrix3dVariable):131 raise IllicitOperatorException(operator, type(result), type(self.scope_manager.last_result))132 result = result.special_multiply(self.scope_manager.last_result)133 if result is None:134 raise IllicitOperatorException(operator, type(result), type(self.scope_manager.last_result))135 self.scope_manager.last_result = result136 def visit_additive_expression(self, additive_expression: AdditiveExpression):137 additive_expression.multiplicative_expressions[0].accept(self)138 result = self.scope_manager.last_result139 for operator, expression in zip(additive_expression.additive_operators,140 additive_expression.multiplicative_expressions[1:]):141 expression.accept(self)142 if operator == TokenType.ADD:143 result += self.scope_manager.last_result144 elif operator == TokenType.SUBTRACT:145 result -= self.scope_manager.last_result146 if result is None:147 raise IllicitOperatorException(operator, type(result), type(self.scope_manager.last_result))148 self.scope_manager.last_result = result149 def visit_expression(self, expression: Expression):150 expression.additive_expressions[0].accept(self)151 result = self.scope_manager.last_result152 for operator, additive_expression in zip(expression.new_operators,153 expression.additive_expressions[1:]):154 additive_expression.accept(self)155 operator_function = self.scope_manager.get_function(operator)156 if not (check_type(result, operator_function.type1) and157 check_type(self.scope_manager.last_result, operator_function.type2)):158 raise TypeMismatchError(result, operator_function.type1, type(result))159 self.__execute_function(operator_function, [result, self.scope_manager.last_result])160 result = self.scope_manager.return_result161 def visit_logical_expression(self, logical_expression: LogicalExpression):162 result = self.scope_manager.last_result163 if isinstance(logical_expression.expression, Condition):164 logical_expression.expression.accept(self)165 if logical_expression.negation_operator:166 result = not result167 self.scope_manager.last_result = result168 else:169 logical_expression.expression.accept(self)170 if logical_expression.negation_operator:171 if isinstance(result, Variable):172 result = result.evaluate_to_bool()173 self.scope_manager.last_result = not result174 def visit_comparison_condition(self, comparison_condition: ComparisonCondition):175 comparison_condition.logical_expression.accept(self)176 condition1 = self.scope_manager.last_result177 operator = comparison_condition.comparison_operator178 if operator is not None:179 comparison_condition.logical_expression2.accept(self)180 condition2 = self.scope_manager.last_result181 if isinstance(condition1, bool) and isinstance(condition2, Variable):182 condition2 = condition2.evaluate_to_bool()183 if isinstance(condition1, Variable) and isinstance(condition2, bool):184 condition1 = condition1.evaluate_to_bool()185 type1 = type(condition1)186 type2 = type(condition2)187 if type1 != type2:188 raise ComparisonTypeMismatchException(type1, type2, operator)189 if operator == TokenType.EQUAL:190 self.scope_manager.last_result = condition1 == condition2191 elif operator == TokenType.NOT_EQUAL:192 self.scope_manager.last_result = condition1 != condition2193 elif operator == TokenType.GREATER_THAN:194 self.scope_manager.last_result = condition1 > condition2195 elif operator == TokenType.LESS_THAN:196 self.scope_manager.last_result = condition1 < condition2197 elif operator == TokenType.GREATER_OR_EQUAL:198 self.scope_manager.last_result = condition1 >= condition2199 elif operator == TokenType.LESS_OR_EQUAL:200 self.scope_manager.last_result = condition1 <= condition2201 elif isinstance(condition1, Variable):202 self.scope_manager.last_result = condition1.evaluate_to_bool()203 def visit_and_condition(self, and_condition: AndCondition):204 for comparison_condition in and_condition.comparison_conditions:205 comparison_condition.accept(self)206 if not self.scope_manager.last_result:207 return208 def visit_condition(self, condition: Condition):209 for and_condition in condition.and_conditions:210 and_condition.accept(self)211 if self.scope_manager.last_result:212 return213 def visit_init_statement(self, init_statement: InitStatement):214 if init_statement.type == TokenType.NUMBER_TYPE:215 if init_statement.argument_list.length == 0:216 self.scope_manager.last_result = NumberVariable('', 0)217 elif init_statement.argument_list.length == 1:218 init_statement.argument_list.expressions[0].accept(self)219 if not isinstance(self.scope_manager.last_result, NumberVariable):220 raise ArgumentTypeException(self.scope_manager.last_result.name,221 'number', type(self.scope_manager.last_result))222 else:223 raise InvalidArgumentsNumberException("To initialize a number variable input 0 or 1 variable.",224 init_statement.argument_list.length)225 elif init_statement.type == TokenType.PIXEL:226 if init_statement.argument_list.length == 0:227 self.scope_manager.last_result = PixelVariable('')228 elif init_statement.argument_list.length == 1:229 init_statement.argument_list.accept(self)230 arguments = self.scope_manager.last_result231 self.scope_manager.last_result = PixelVariable('',232 arguments[0].value,233 arguments[0].value,234 arguments[0].value)235 elif init_statement.argument_list.length == 3:236 init_statement.argument_list.accept(self)237 arguments = self.scope_manager.last_result238 self.scope_manager.last_result = PixelVariable('',239 arguments[0].value,240 arguments[1].value,241 arguments[2].value)242 else:243 raise InvalidArgumentsNumberException("To initialize a pixel variable input 0 or 1 or 3 variables.",244 init_statement.argument_list.length)245 elif init_statement.type == TokenType.MATRIX:246 if init_statement.argument_list.length == 1:247 init_statement.argument_list.accept(self)248 arguments = self.scope_manager.last_result249 row = [0] * arguments[0].value250 self.scope_manager.last_result = MatrixVariable('', [row])251 elif init_statement.argument_list.length == 2:252 init_statement.argument_list.accept(self)253 arguments = self.scope_manager.last_result254 rows = []255 for i in range(arguments[0].value):256 rows.append([0] * arguments[1].value)257 self.scope_manager.last_result = MatrixVariable('', rows)258 elif init_statement.argument_list.length == 3:259 init_statement.argument_list.accept(self)260 arguments = self.scope_manager.last_result261 matrices = []262 for m in range(arguments[0].value):263 rows = []264 for r in range(arguments[1].value):265 rows.append([0] * arguments[2].value)266 matrices.append(MatrixVariable('', rows))267 self.scope_manager.last_result = Matrix3dVariable('', matrices)268 else:269 raise InvalidArgumentsNumberException("To initialize a matrix variable input 0 or 2 or 3 variables.",270 init_statement.argument_list.length)271 else:272 raise InvalidVariableTypeException(init_statement.type)273 def visit_return_statement(self, return_statement: ReturnStatement):274 if return_statement.expression is None:275 self.scope_manager.return_result = None276 else:277 return_statement.expression.accept(self)278 self.scope_manager.return_result = self.scope_manager.last_result279 def visit_operator_definition(self, operator_definition: OperatorDefinition):280 operator_definition.block.accept(self)281 def visit_assignment(self, assignment: Assignment):282 assignment.expression.accept(self)283 if assignment.reference is not None:284 return_result = self.scope_manager.return_result285 self.scope_manager.return_result = self.scope_manager.last_result.value286 assignment.reference.accept(self)287 self.scope_manager.return_result = return_result288 if assignment.matrix_lookup is not None:289 return_result = self.scope_manager.return_result290 self.scope_manager.return_result = self.scope_manager.last_result.value291 assignment.matrix_lookup.accept(self)292 self.scope_manager.return_result = return_result293 if assignment.id is not None:294 self.scope_manager.last_result.name = assignment.id295 self.scope_manager.add_update_variable(assignment.id, self.scope_manager.last_result)296 def visit_reference(self, reference: Reference):297 reference_result = None298 variable = self.scope_manager.get_variable(reference.id1)299 if isinstance(variable, PixelVariable):300 pixel = variable301 if reference.id2 == 'r':302 if isinstance(self.scope_manager.return_result, int):303 # value assigned to pixel channel304 pixel.set_r(self.scope_manager.return_result)305 reference_result = pixel306 else:307 # pixel channel value assigned to variable308 reference_result = NumberVariable('', pixel.r)309 elif reference.id2 == 'g':310 if isinstance(self.scope_manager.return_result, int):311 # value assigned to pixel channel312 pixel.set_g(self.scope_manager.return_result)313 reference_result = pixel314 else:315 # pixel channel value assigned to variable316 reference_result = NumberVariable('', pixel.g)317 elif reference.id2 == 'b':318 if isinstance(self.scope_manager.return_result, int):319 # value assigned to pixel channel320 pixel.set_b(self.scope_manager.return_result)321 reference_result = pixel322 else:323 # pixel channel value assigned to variable324 reference_result = NumberVariable('', pixel.b)325 elif isinstance(variable, MatrixVariable) or isinstance(variable, Matrix3dVariable):326 matrix = variable327 if reference.id2 == 'xdim':328 reference_result = NumberVariable('', matrix.xdim)329 elif reference.id2 == 'ydim':330 reference_result = NumberVariable('', matrix.ydim)331 elif reference.id2 == 'zdim' and isinstance(matrix, Matrix3dVariable):332 reference_result = NumberVariable('', matrix.zdim)333 elif reference.id2 == 'dims':334 if isinstance(matrix, MatrixVariable):335 reference_result = NumberVariable('', 2)336 else:337 reference_result = NumberVariable('', 3)338 if reference_result is not None:339 self.scope_manager.last_result = reference_result340 else:341 raise UndefinedReferenceException(reference.id2)342 def visit_matrix_lookup(self, matrix_lookup: MatrixLookup):343 indices = []344 for index in matrix_lookup.indices:345 index.accept(self)346 indices.append(self.scope_manager.last_result.value)347 matrix = self.scope_manager.get_variable(matrix_lookup.id)348 if isinstance(matrix, MatrixVariable):349 if len(indices) != 2:350 raise InvalidArgumentsNumberException("To look up matrix value use 2 indices.", len(indices))351 if indices[0] >= matrix.ydim or indices[1] >= matrix.xdim:352 raise IndexOutOfRangeError()353 if isinstance(self.scope_manager.return_result, int):354 # value assigned to matrix field355 matrix.rows[indices[0]][indices[1]] = self.scope_manager.return_result356 self.scope_manager.last_result = matrix357 else:358 # matrix field value assigned to variable359 self.scope_manager.last_result = NumberVariable('', matrix.rows[indices[0]][indices[1]])360 if isinstance(matrix, Matrix3dVariable):361 if len(indices) != 3:362 raise InvalidArgumentsNumberException("To look up matrix value use 3 indices.", len(indices))363 if indices[0] >= matrix.zdim or indices[1] >= matrix.ydim or indices[2] >= matrix.xdim:364 raise IndexOutOfRangeError()365 if isinstance(self.scope_manager.return_result, int):366 # value assigned to matrix field367 matrix.matrices[indices[0]].rows[indices[1]][indices[2]] = self.scope_manager.return_result368 self.scope_manager.last_result = matrix369 else:370 # matrix field value assigned to variable371 self.scope_manager.last_result = \372 NumberVariable('', matrix.matrices[indices[0]].rows[indices[1]][indices[2]])373 def __execute_function(self, function, arguments):374 if not function.verify_arguments(arguments):375 raise InvalidArgumentsNumberException("To call " + function.id + " " + str(len(function.parameter_list)) +376 " arguments were expected.", len(arguments))377 self.scope_manager.switch_to_new_scope(function.id)378 for argument, parameter in zip(arguments, function.parameter_list):379 self.scope_manager.add_variable(parameter, argument)380 function.accept(self)381 self.scope_manager.switch_to_previous_scope()382 def __load_built_in_functions(self):383 builtin_functions = [PrintFunction(), RandomPixelFunction(), DeterminantFunction()]384 for function_definition in builtin_functions:385 self.scope_manager.add_function(function_definition.id, function_definition)386 def __return_result(self):387 if self.scope_manager.last_result is None:388 return 0389 if isinstance(self.scope_manager.last_result, NumberVariable):390 return self.scope_manager.last_result.value391 if self.scope_manager.last_result is not False:392 return 0393 return -1394def check_type(variable, expected_type):395 return (isinstance(variable, NumberVariable) and expected_type == TokenType.NUMBER_TYPE) or \396 (isinstance(variable, PixelVariable) and expected_type == TokenType.PIXEL) or \...

Full Screen

Full Screen

scope_check.py

Source:scope_check.py Github

copy

Full Screen

...24 """25 A mixin class for validation that a given scope manager implementation26 satisfies the requirements of the OpenTracing API.27 """28 def scope_manager(self):29 raise NotImplementedError('Subclass must implement scope_manager()')30 def run_test(self, test_fn):31 """32 Utility method that can be optionally defined by ScopeManager33 implementers to run the passed test_fn() function34 in a given environment, such as a coroutine or greenlet.35 By default, it simply runs the passed test_fn() function36 in the current thread.37 """38 test_fn()39 def test_missing_active_external(self):40 # test that 'active' does not fail outside the run_test()41 # implementation (greenlet or coroutine).42 scope_manager = self.scope_manager()43 assert scope_manager.active is None44 def test_missing_active(self):45 def fn():46 scope_manager = self.scope_manager()47 assert scope_manager.active is None48 self.run_test(fn)49 def test_activate(self):50 def fn():51 scope_manager = self.scope_manager()52 span = mock.MagicMock(spec=Span)53 scope = scope_manager.activate(span, False)54 assert scope is not None55 assert scope_manager.active is scope56 scope.close()57 assert span.finish.call_count == 058 assert scope_manager.active is None59 self.run_test(fn)60 def test_activate_external(self):61 # test that activate() does not fail outside the run_test()62 # implementation (greenlet or corotuine).63 scope_manager = self.scope_manager()64 span = mock.MagicMock(spec=Span)65 scope = scope_manager.activate(span, False)66 assert scope is not None67 assert scope_manager.active is scope68 scope.close()69 assert span.finish.call_count == 070 assert scope_manager.active is None71 def test_activate_finish_on_close(self):72 def fn():73 scope_manager = self.scope_manager()74 span = mock.MagicMock(spec=Span)75 scope = scope_manager.activate(span, True)76 assert scope is not None77 assert scope_manager.active is scope78 scope.close()79 assert span.finish.call_count == 180 assert scope_manager.active is None81 self.run_test(fn)82 def test_activate_nested(self):83 def fn():84 # when a Scope is closed, the previous one must be re-activated.85 scope_manager = self.scope_manager()86 parent_span = mock.MagicMock(spec=Span)87 child_span = mock.MagicMock(spec=Span)88 with scope_manager.activate(parent_span, True) as parent:89 assert parent is not None90 assert scope_manager.active is parent91 with scope_manager.activate(child_span, True) as child:92 assert child is not None93 assert scope_manager.active is child94 assert scope_manager.active is parent95 assert parent_span.finish.call_count == 196 assert child_span.finish.call_count == 197 assert scope_manager.active is None98 self.run_test(fn)99 def test_activate_finish_on_close_nested(self):100 def fn():101 # finish_on_close must be correctly handled102 scope_manager = self.scope_manager()103 parent_span = mock.MagicMock(spec=Span)104 child_span = mock.MagicMock(spec=Span)105 parent = scope_manager.activate(parent_span, False)106 with scope_manager.activate(child_span, True):107 pass108 parent.close()109 assert parent_span.finish.call_count == 0110 assert child_span.finish.call_count == 1111 assert scope_manager.active is None112 self.run_test(fn)113 def test_close_wrong_order(self):114 def fn():115 # only the active `Scope` can be closed116 scope_manager = self.scope_manager()117 parent_span = mock.MagicMock(spec=Span)118 child_span = mock.MagicMock(spec=Span)119 parent = scope_manager.activate(parent_span, True)120 child = scope_manager.activate(child_span, True)121 parent.close()122 assert parent_span.finish.call_count == 0123 assert scope_manager.active == child...

Full Screen

Full Screen

tracer.py

Source:tracer.py Github

copy

Full Screen

1import time2import uuid3from opentracing import Format, Tracer, UnsupportedFormatException4from opentracing.scope_managers import ThreadLocalScopeManager5from .text_propagator import TextPropagator6from .span import Span, SpanContext7class HaystackTracer(Tracer):8 def __init__(self,9 service_name,10 recorder,11 scope_manager=None,12 common_tags=None,13 use_shared_spans=False):14 """15 Initialize a Haystack Tracer instance.16 :param service_name: The service name to which all spans will belong.17 :param recorder: The recorder (dispatcher) implementation which handles18 finished spans.19 :param scope_manager: An optional parameter to override the default20 ThreadLocal scope manager.21 :param common_tags: An optional dictionary of tags which should be22 applied to all created spans for this service23 :param use_shared_spans: A boolean indicating whether or not to use24 shared spans. This is when client/server spans share the same span id.25 Default is to use unique span ids.26 """27 scope_manager = ThreadLocalScopeManager() if scope_manager is None \28 else scope_manager29 super().__init__(scope_manager)30 self._propagators = {}31 self._common_tags = {} if common_tags is None else common_tags32 self.service_name = service_name33 self.recorder = recorder34 self.use_shared_spans = use_shared_spans35 self.register_propagator(Format.TEXT_MAP, TextPropagator())36 self.register_propagator(Format.HTTP_HEADERS, TextPropagator())37 def register_propagator(self, format, propagator):38 """Register a propagator with this Tracer.39 :param string format: a Format identifier like Format.TEXT_MAP40 :param Propagator propagator: a Propagator instance to handle41 inject/extract calls42 """43 self._propagators[format] = propagator44 def start_active_span(self,45 operation_name,46 child_of=None,47 references=None,48 tags=None,49 start_time=None,50 ignore_active_span=False,51 finish_on_close=True):52 span = self.start_span(operation_name=operation_name,53 child_of=child_of,54 references=references,55 tags=tags,56 start_time=start_time,57 ignore_active_span=ignore_active_span)58 return self.scope_manager.activate(span, finish_on_close)59 def start_span(self,60 operation_name=None,61 child_of=None,62 references=None,63 tags=None,64 start_time=None,65 ignore_active_span=False):66 start_time = time.time() if start_time is None else start_time67 # Check for an existing ctx in `references`68 parent_ctx = None69 if child_of is not None:70 parent_ctx = (child_of if isinstance(child_of, SpanContext)71 else child_of.context)72 elif references is not None and len(references) > 0:73 parent_ctx = references[0].referenced_context74 # Check for an active span in scope manager75 if not ignore_active_span and parent_ctx is None:76 scope = self.scope_manager.active77 if scope is not None:78 parent_ctx = scope.span.context79 new_ctx = SpanContext(span_id=format(uuid.uuid4()))80 if parent_ctx is not None:81 new_ctx.trace_id = parent_ctx.trace_id82 if parent_ctx.baggage is not None:83 new_ctx._baggage = parent_ctx.baggage.copy()84 if self.use_shared_spans:85 new_ctx.span_id = parent_ctx.span_id86 new_ctx.parent_id = parent_ctx.parent_id87 else:88 new_ctx.parent_id = parent_ctx.span_id89 else:90 new_ctx.trace_id = format(uuid.uuid4())91 # Set common tags92 if self._common_tags:93 tags = {**self._common_tags, **tags} if tags else \94 self._common_tags.copy()95 return Span(self,96 operation_name=operation_name,97 context=new_ctx,98 tags=tags,99 start_time=start_time)100 def inject(self, span_context, format, carrier):101 if format in self._propagators:102 self._propagators[format].inject(span_context, carrier)103 else:104 raise UnsupportedFormatException()105 def extract(self, format, carrier):106 if format in self._propagators:107 return self._propagators[format].extract(carrier)108 else:109 raise UnsupportedFormatException()110 def record(self, span):111 self.recorder.record_span(span)112 def __enter__(self):113 return self114 def __exit__(self, exc_type, exc_val, exc_tb):...

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