Skip to content

Commit 617831d

Browse files
feature:minor
1. Added count function for strings str.count().
1 parent 5b51c3c commit 617831d

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

src/lpython/semantics/python_ast_to_asr.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6791,6 +6791,28 @@ class BodyVisitor : public CommonVisitor<BodyVisitor> {
67916791
[&](const std::string &msg, const Location &loc) {
67926792
throw SemanticError(msg, loc); });
67936793
return;
6794+
} else if(attr_name == "count") {
6795+
if(args.size() != 1) {
6796+
throw SemanticError("str.count() takes one argument for now.", loc);
6797+
}
6798+
ASR::expr_t *arg_value = args[0].m_value;
6799+
ASR::ttype_t *arg_value_type = ASRUtils::expr_type(arg_value);
6800+
if (!ASRUtils::is_character(*arg_value_type)) {
6801+
throw SemanticError("str.count() takes one argument of type: str", loc);
6802+
}
6803+
6804+
fn_call_name = "_lpython_str_count";
6805+
ASR::call_arg_t str;
6806+
str.loc = loc;
6807+
str.m_value = s_var;
6808+
6809+
ASR::call_arg_t value;
6810+
value.loc = loc;
6811+
value.m_value = args[0].m_value;
6812+
6813+
// Push string and substring argument on top of Vector (or Function Arguments Stack basically)
6814+
fn_args.push_back(al, str);
6815+
fn_args.push_back(al, value);
67946816
} else if(attr_name.size() > 2 && attr_name[0] == 'i' && attr_name[1] == 's') {
67956817
/*
67966818
String Validation Methods i.e all "is" based functions are handled here

src/lpython/semantics/python_comptime_eval.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ struct PythonIntrinsicProcedures {
7777
// The following functions for string methods are not used
7878
// for evaluation.
7979
{"_lpython_str_capitalize", {m_builtin, &not_implemented}},
80+
{"_lpython_str_count", {m_builtin, &not_implemented}},
8081
{"_lpython_str_lower", {m_builtin, &not_implemented}},
8182
{"_lpython_str_upper", {m_builtin, &not_implemented}},
8283
{"_lpython_str_find", {m_builtin, &not_implemented}},

src/runtime/lpython_builtin.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,22 @@ def _lpython_str_capitalize(x: str) -> str:
722722
res = chr(val) + res[1:]
723723
return res
724724

725+
726+
@overload
727+
def _lpython_str_count(x: str, y: str) -> i32:
728+
assert (len(y) == 0), 'The length y should one for now.'
729+
730+
count : i32
731+
count = 0
732+
733+
i: str
734+
735+
for i in x:
736+
count += i32(i == y)
737+
738+
return count
739+
740+
725741
@overload
726742
def _lpython_str_lower(x: str) -> str:
727743
res: str

0 commit comments

Comments
 (0)