Skip to content

Commit

Permalink
compiler: optimize code generation for constant string indexing expre…
Browse files Browse the repository at this point in the history
…ssions
  • Loading branch information
mertcandav committed Aug 11, 2024
1 parent d335edf commit 980a933
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
25 changes: 25 additions & 0 deletions api/str.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,31 @@ namespace jule
return s;
}

// Returns element by index.
// Includes safety checking.
// Designed for constant strings.
static jule::U8 at(
#ifndef __JULE_ENABLE__PRODUCTION
const char *file,
#endif
const jule::U8 *s, const jule::Int n, const jule::Int i) noexcept
{
#ifndef __JULE_DISABLE__SAFETY
if (n == 0 || i < 0 || n <= i)
{
std::string error;
__JULE_WRITE_ERROR_INDEX_OUT_OF_RANGE(error, i, n);
error += "\nruntime: string indexing with out of range index";
#ifndef __JULE_ENABLE__PRODUCTION
error += "\nfile: ";
error += file;
#endif
jule::panic(error);
}
#endif
return s[i];
}

Str(void) : _len(0) {};
Str(const jule::Str &src) : buffer(src.buffer), _len(src._len), _slice(src._slice) {}
Str(jule::Str &&src) : buffer(std::move(src.buffer)), _len(src._len), _slice(src._slice) {}
Expand Down
20 changes: 20 additions & 0 deletions src/julec/obj/cxx/expr.jule
Original file line number Diff line number Diff line change
Expand Up @@ -840,6 +840,26 @@ impl exprCoder {
}

fn indexing(mut &self, mut m: &IndexingExprModel) {
match type m.Expr.Model {
| &Const:
// Cosntant string indexed. Use fast way, avoid making literal.
self.oc.write(typeCoder.Str + "::at(")
if !env::Production {
self.oc.write("\"")
self.oc.locInfo(m.Token)
self.oc.write("\", ")
}
self.oc.write("reinterpret_cast<const " + typeCoder.U8 + "*>(")
s := (&Const)(m.Expr.Model).ReadStr()
cstrLit(self.oc.Buf, s)
self.oc.write("), ")
self.oc.write(conv::Itoa(len(s)))
self.oc.write(", ")
self.possibleRefExpr(m.Index.Model)
self.oc.write(")")
ret
}

self.possibleRefExpr(m.Expr.Model)
// Index access with safety measures.
match {
Expand Down
1 change: 1 addition & 0 deletions src/julec/obj/cxx/type.jule
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ impl typeCoder {
const Bool = "jule::Bool"
const Int = "jule::Int"
const Uintptr = "jule::Uintptr"
const U8 = "jule::U8"

static fn new(mut &oc: &ObjectCoder): &typeCoder {
mut tc := &typeCoder{oc: oc}
Expand Down

0 comments on commit 980a933

Please sign in to comment.