better bad cast error message

This commit is contained in:
VaclavT 2021-10-07 07:24:22 +02:00
parent f92cefc004
commit b68987fdd7
1 changed files with 11 additions and 16 deletions

27
ml.cpp
View File

@ -35,7 +35,11 @@
#define INVALID_LAMBDA "invalid lambda"
#define INVALID_BIN_OP "invalid binary operation"
#define INVALID_ORDER "cannot order expression"
#define BAD_CAST "cannot cast"
#define BAD_CAST_INT "cannot cast as int"
#define BAD_CAST_FLOAT "cannot cast as float"
#define BAD_CAST_STRING "cannot cast as string"
#define BAD_CAST_ATOM "cannot cast as atom"
#define BAD_CAST_LIST "cannot cast as list"
#define ATOM_NOT_DEFINED "atom not defined"
#define INTERNAL_ERROR "internal virtual machine error"
#define INDEX_OUT_OF_RANGE "index out of range"
@ -181,42 +185,33 @@ bool MlValue::is_list() const {
return type == LIST;
}
// Get the "truthy" boolean value of this value.
bool MlValue::as_bool() const {
return type != NIL && *this != MlValue(0l); // TODO remove 0 as false
}
// Get this item's integer value
long MlValue::as_int() const {
return cast_to_int().stack_data.i;
}
// Get this item's floating point value
double MlValue::as_float() const {
return cast_to_float().stack_data.f;
}
// Get this item's string value
std::string MlValue::as_string() const {
// If this item is not a string, throw a cast error.
if (type != STRING)
throw MlError(*this, MlEnvironment(), BAD_CAST);
throw MlError(*this, MlEnvironment(), BAD_CAST_STRING);
return str;
}
// Get this item's atom value
std::string MlValue::as_atom() const {
// If this item is not an atom, throw a cast error.
if (type != ATOM)
throw MlError(*this, MlEnvironment(), BAD_CAST);
throw MlError(*this, MlEnvironment(), BAD_CAST_ATOM);
return str;
}
// Get this item's list value
std::vector<MlValue> MlValue::as_list() const {
// If this item is not a list, throw a cast error.
if (type != LIST)
throw MlError(*this, MlEnvironment(), BAD_CAST);
throw MlError(*this, MlEnvironment(), BAD_CAST_LIST);
return list;
}
@ -254,7 +249,7 @@ MlValue MlValue::cast_to_int() const {
case STRING:
return MlValue(std::stol(str));
default:
throw MlError(*this, MlEnvironment(), BAD_CAST);
throw MlError(*this, MlEnvironment(), BAD_CAST_INT);
}
}
@ -268,7 +263,7 @@ MlValue MlValue::cast_to_float() const {
case STRING:
return MlValue(std::stod(str));
default:
throw MlError(*this, MlEnvironment(), BAD_CAST);
throw MlError(*this, MlEnvironment(), BAD_CAST_FLOAT);
}
}
@ -282,7 +277,7 @@ MlValue MlValue::cast_to_string() const {
case STRING:
return *this;
default:
throw MlError(*this, MlEnvironment(), BAD_CAST);
throw MlError(*this, MlEnvironment(), BAD_CAST_STRING);
}
}