fix: guard against non-string toString in IO.print and IO.write

Add writeObject_ helper that checks if obj.toString returns a String before
writing it, falling back to "[invalid toString]" otherwise. Update print,
write, and printList_ to use the new helper instead of calling toString
directly. Include test cases for both IO.print and IO.write with a class
whose toString returns an integer.
This commit is contained in:
Bob Nystrom
2015-01-08 15:53:37 +00:00
parent 6c2d673638
commit 3f126945df
4 changed files with 35 additions and 6 deletions
+12 -3
View File
@@ -13,7 +13,7 @@ static const char* libSource =
" }\n"
"\n"
" static print(obj) {\n"
" IO.writeString_(obj.toString)\n"
" IO.writeObject_(obj)\n"
" IO.writeString_(\"\n\")\n"
" return obj\n"
" }\n"
@@ -79,14 +79,23 @@ static const char* libSource =
" }\n"
"\n"
" static printList_(objects) {\n"
" for (object in objects) IO.writeString_(object.toString)\n"
" for (object in objects) IO.writeObject_(object)\n"
" IO.writeString_(\"\n\")\n"
" }\n"
"\n"
" static write(obj) {\n"
" IO.writeString_(obj.toString)\n"
" IO.writeObject_(obj)\n"
" return obj\n"
" }\n"
"\n"
" static writeObject_(obj) {\n"
" var string = obj.toString\n"
" if (string is String) {\n"
" IO.writeString_(string)\n"
" } else {\n"
" IO.writeString_(\"[invalid toString]\")\n"
" }\n"
" }\n"
"}\n";
static void ioWriteString(WrenVM* vm)