Skip to content

Commit 46cde59

Browse files
committed
Catch key not found error
1 parent 456e760 commit 46cde59

File tree

5 files changed

+43
-1
lines changed

5 files changed

+43
-1
lines changed

src/libasr/codegen/llvm_utils.cpp

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1636,8 +1636,24 @@ namespace LCompilers {
16361636
}
16371637
llvm_utils->start_new_block(mergeBB);
16381638
llvm::Value* pos = LLVM::CreateLoad(*builder, pos_ptr);
1639+
// Check if the actual key is present or not
1640+
llvm::Value* is_key_matching = llvm_utils->is_equal_by_value(key,
1641+
llvm_utils->list_api->read_item(key_list, pos, false, module,
1642+
LLVM::is_llvm_struct(key_asr_type)), module, key_asr_type);
1643+
1644+
llvm_utils->create_if_else(is_key_matching, [&]() {
1645+
}, [&]() {
1646+
std::string message = "The dict does not contain the specified key";
1647+
llvm::Value *fmt_ptr = builder->CreateGlobalStringPtr("KeyError: %s\n");
1648+
llvm::Value *fmt_ptr2 = builder->CreateGlobalStringPtr(message);
1649+
print_error(context, module, *builder, {fmt_ptr, fmt_ptr2});
1650+
int exit_code_int = 1;
1651+
llvm::Value *exit_code = llvm::ConstantInt::get(context,
1652+
llvm::APInt(32, exit_code_int));
1653+
exit(context, module, *builder, exit_code);
1654+
});
16391655
llvm::Value* item = llvm_utils->list_api->read_item(value_list, pos,
1640-
false, module, true);
1656+
false, module, true);;
16411657
return item;
16421658
}
16431659

tests/errors/test_dict14.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from lpython import i32
2+
3+
def key_not_present():
4+
x: dict[i32, i32] = {}
5+
x = {1: 1, 2: 2}
6+
print(x[10])
7+
8+
key_not_present()
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"basename": "runtime-test_dict14-421fe53",
3+
"cmd": "lpython {infile}",
4+
"infile": "tests/errors/test_dict14.py",
5+
"infile_hash": "c81e4a1e050c87d04f537b49fcfb0b479a5ce3ed7735f90d2c347dba",
6+
"outfile": null,
7+
"outfile_hash": null,
8+
"stdout": null,
9+
"stdout_hash": null,
10+
"stderr": "runtime-test_dict14-421fe53.stderr",
11+
"stderr_hash": "cb46ef04db0862506d688ebe8830a50afaaead9b0d29b0c007dd149a",
12+
"returncode": 1
13+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
KeyError: The dict does not contain the specified key

tests/tests.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,10 @@ asr = true
808808
filename = "errors/test_dict13.py"
809809
asr = true
810810

811+
[[test]]
812+
filename = "errors/test_dict14.py"
813+
run = true
814+
811815
[[test]]
812816
filename = "errors/test_zero_division.py"
813817
asr = true

0 commit comments

Comments
 (0)