Skip to content

Commit

Permalink
feature:minor
Browse files Browse the repository at this point in the history
1. Added count function for strings str.count().
  • Loading branch information
SudhanshuJoshi09 committed Sep 27, 2023
1 parent 5b51c3c commit 617831d
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/lpython/semantics/python_ast_to_asr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6791,6 +6791,28 @@ class BodyVisitor : public CommonVisitor<BodyVisitor> {
[&](const std::string &msg, const Location &loc) {
throw SemanticError(msg, loc); });
return;
} else if(attr_name == "count") {
if(args.size() != 1) {
throw SemanticError("str.count() takes one argument for now.", loc);
}
ASR::expr_t *arg_value = args[0].m_value;
ASR::ttype_t *arg_value_type = ASRUtils::expr_type(arg_value);
if (!ASRUtils::is_character(*arg_value_type)) {
throw SemanticError("str.count() takes one argument of type: str", loc);
}

fn_call_name = "_lpython_str_count";
ASR::call_arg_t str;
str.loc = loc;
str.m_value = s_var;

ASR::call_arg_t value;
value.loc = loc;
value.m_value = args[0].m_value;

// Push string and substring argument on top of Vector (or Function Arguments Stack basically)
fn_args.push_back(al, str);
fn_args.push_back(al, value);
} else if(attr_name.size() > 2 && attr_name[0] == 'i' && attr_name[1] == 's') {
/*
String Validation Methods i.e all "is" based functions are handled here
Expand Down
1 change: 1 addition & 0 deletions src/lpython/semantics/python_comptime_eval.h
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ struct PythonIntrinsicProcedures {
// The following functions for string methods are not used
// for evaluation.
{"_lpython_str_capitalize", {m_builtin, &not_implemented}},
{"_lpython_str_count", {m_builtin, &not_implemented}},
{"_lpython_str_lower", {m_builtin, &not_implemented}},
{"_lpython_str_upper", {m_builtin, &not_implemented}},
{"_lpython_str_find", {m_builtin, &not_implemented}},
Expand Down
16 changes: 16 additions & 0 deletions src/runtime/lpython_builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,22 @@ def _lpython_str_capitalize(x: str) -> str:
res = chr(val) + res[1:]
return res


@overload
def _lpython_str_count(x: str, y: str) -> i32:
assert (len(y) == 0), 'The length y should one for now.'

count : i32
count = 0

i: str

for i in x:
count += i32(i == y)

return count


@overload
def _lpython_str_lower(x: str) -> str:
res: str
Expand Down

0 comments on commit 617831d

Please sign in to comment.