From ad9b47b72fb664c518a8e55471c58a3e21986cd0 Mon Sep 17 00:00:00 2001 From: bmcq-0 <66541602+bmcq-0@users.noreply.github.com> Date: Fri, 5 Nov 2021 16:24:30 -0400 Subject: [PATCH] Fold length operations when argument is a constant string (#141) Co-authored-by: Arseny Kapoulkine --- Compiler/src/Compiler.cpp | 5 +++++ tests/Compiler.test.cpp | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/Compiler/src/Compiler.cpp b/Compiler/src/Compiler.cpp index 7750a1d..4c86b6f 100644 --- a/Compiler/src/Compiler.cpp +++ b/Compiler/src/Compiler.cpp @@ -2900,6 +2900,11 @@ struct Compiler break; case AstExprUnary::Len: + if (arg.type == Constant::Type_String) + { + result.type = Constant::Type_Number; + result.valueNumber = double(arg.valueString.size); + } break; default: diff --git a/tests/Compiler.test.cpp b/tests/Compiler.test.cpp index bbac330..1389bfe 100644 --- a/tests/Compiler.test.cpp +++ b/tests/Compiler.test.cpp @@ -1168,6 +1168,17 @@ RETURN R0 1 )"); } +TEST_CASE("ConstantFoldStringLen") +{ + CHECK_EQ("\n" + compileFunction0("return #'string', #'', #'a', #('b')"), R"( +LOADN R0 6 +LOADN R1 0 +LOADN R2 1 +LOADN R3 1 +RETURN R0 4 +)"); +} + TEST_CASE("ConstantFoldCompare") { // ordered comparisons