Fix an infinite loop during message generation.
authorDavid Neto <dneto@google.com>
Fri, 11 Sep 2015 16:04:03 +0000 (12:04 -0400)
committerDavid Neto <dneto@google.com>
Mon, 26 Oct 2015 16:55:33 +0000 (12:55 -0400)
Rename getWord to spvGetWord and unit test it.

source/text.cpp
source/text.h
test/TextToBinary.cpp

index 5912558..5f81193 100644 (file)
@@ -53,20 +53,23 @@ struct spv_named_id_table_t {
 
 // Text API
 
-std::string getWord(const char *str) {
+std::string spvGetWord(const char *str) {
   size_t index = 0;
   while (true) {
     switch (str[index]) {
       case '\0':
       case '\t':
+      case '\v':
+      case '\r':
       case '\n':
       case ' ':
-        break;
+        return std::string(str, str + index);
       default:
         index++;
     }
   }
-  return std::string(str, str + index);
+  assert(0 && "Unreachable");
+  return ""; // Make certain compilers happy.
 }
 
 spv_named_id_table spvNamedIdTableCreate() {
@@ -674,7 +677,7 @@ spv_result_t spvTextEncodeOpcode(
   spv_opcode_desc opcodeEntry;
   error = spvOpcodeTableNameLookup(opcodeTable, pInstName, &opcodeEntry);
   spvCheck(error, DIAGNOSTIC << "Invalid Opcode name '"
-                             << getWord(text->str + position->index) << "'";
+                             << spvGetWord(text->str + position->index) << "'";
            return error);
   if (SPV_ASSEMBLY_SYNTAX_FORMAT_ASSIGNMENT == format) {
     // If this instruction has <result-id>, check it follows AAF.
index 197f89f..72d96d5 100644 (file)
@@ -66,6 +66,16 @@ typedef spv_named_id_table_t *spv_named_id_table;
 
 // Functions
 
+/// @brief Returns the word at the beginning of the given string.
+///
+/// A word ends at the first space, tab, form feed, carriage return, newline,
+/// or at the end of the string.
+///
+/// @param[in] str the source string
+///
+/// @return word as a string
+std::string spvGetWord(const char* str);
+
 /// @brief Advance text to the start of the next line
 ///
 /// @param[in] text to be parsed
index 2c153d9..c7eb261 100644 (file)
@@ -37,6 +37,23 @@ namespace {
 using spvutils::BitwiseCast;
 using test_fixture::TextToBinaryTest;
 
+TEST(GetWord, Simple) {
+  EXPECT_EQ("", spvGetWord(""));
+  EXPECT_EQ("", spvGetWord("\0a"));
+  EXPECT_EQ("", spvGetWord(" a"));
+  EXPECT_EQ("", spvGetWord("\ta"));
+  EXPECT_EQ("", spvGetWord("\va"));
+  EXPECT_EQ("", spvGetWord("\ra"));
+  EXPECT_EQ("", spvGetWord("\na"));
+  EXPECT_EQ("abc", spvGetWord("abc"));
+  EXPECT_EQ("abc", spvGetWord("abc "));
+  EXPECT_EQ("abc", spvGetWord("abc\t"));
+  EXPECT_EQ("abc", spvGetWord("abc\r"));
+  EXPECT_EQ("abc", spvGetWord("abc\v"));
+  EXPECT_EQ("abc", spvGetWord("abc\n"));
+}
+
+// TODO(dneto): Aliasing like this relies on undefined behaviour. Fix this.
 union char_word_t {
   char cs[4];
   uint32_t u;