diff --git a/xs/src/libslic3r/ConditionalGcode.cpp b/xs/src/libslic3r/ConditionalGcode.cpp index bfc74a55a..ee28b7a7c 100644 --- a/xs/src/libslic3r/ConditionalGcode.cpp +++ b/xs/src/libslic3r/ConditionalGcode.cpp @@ -24,11 +24,28 @@ static inline void trim(std::string &s) { ltrim(s); rtrim(s); } + +static inline void replace_substr(std::string &str, const std::string& from, const std::string& to) +{ + size_t start_pos = 0; + while((start_pos = str.find(from, start_pos)) != std::string::npos) { + str.replace(start_pos, from.length(), to); + start_pos += to.length(); // Handles case where 'to' is a substring of 'from' + } +} /// Start of recursive function to parse gcode file. std::string apply_math(const std::string& input) { - return expression(input); + std::string temp_string(input); + replace_substr(temp_string, std::string("\\{"), std::string("\x80")); + replace_substr(temp_string, std::string("\\}"), std::string("\x81")); + temp_string = expression(temp_string); + replace_substr(temp_string, std::string("\x80"), std::string("{")); + replace_substr(temp_string, std::string("\x81"), std::string("}")); + return temp_string; } + + /// Evaluate expressions with exprtk /// Everything must resolve to a number. std::string evaluate(const std::string& expression_string) { @@ -44,7 +61,7 @@ std::string evaluate(const std::string& expression_string) { #if SLIC3R_DEBUG std::cerr << __FILE__ << ":" << __LINE__ << " "<< "Failed to parse: " << expression_string.c_str() << std::endl; #endif - result << "{" << expression_string << "}"; + result << "" << expression_string << ""; } std::string output = result.str(); trim(output); diff --git a/xs/t/24_gcodemath.t b/xs/t/24_gcodemath.t index 1aeba40d0..70663809e 100644 --- a/xs/t/24_gcodemath.t +++ b/xs/t/24_gcodemath.t @@ -4,7 +4,7 @@ use strict; use warnings; use Slic3r::XS; -use Test::More tests => 6; +use Test::More tests => 7; { { my $test_string = "{if{3 == 4}} string"; @@ -37,10 +37,16 @@ use Test::More tests => 6; my $result = Slic3r::ConditionalGCode::apply_math($test_string); is $result, "M104 S20; Sets temp to 20", 'Bracket replacement works with math ops'; } + { + my $test_string = "M104 S\\{a\\}; Sets temp to {4*5}"; + + my $result = Slic3r::ConditionalGCode::apply_math($test_string); + is $result, "M104 S{a}; Sets temp to 20", 'Escaped string emittal.'; + } { my $test_string = "M104 S{a}; Sets temp to {4*5}"; my $result = Slic3r::ConditionalGCode::apply_math($test_string); - is $result, "M104 S{a}; Sets temp to 20", 'Original string emittal on failure to parse'; + is $result, "M104 Sa; Sets temp to 20", 'string (minus brackets) on failure to parse.'; } }