reader/spirv: Allow leading underscore in identifiers

Bug: tint:1292
Change-Id: I738c981f503545075115101a3ead30941a19d95a
Reviewed-on: https://dawn-review.googlesource.com/c/tint/+/72320
Reviewed-by: David Neto <dneto@google.com>
Kokoro: Kokoro <noreply+kokoro@google.com>
Commit-Queue: Ben Clayton <bclayton@google.com>
diff --git a/src/reader/spirv/parser_impl.cc b/src/reader/spirv/parser_impl.cc
index 6e92c3e..544fcfe 100644
--- a/src/reader/spirv/parser_impl.cc
+++ b/src/reader/spirv/parser_impl.cc
@@ -750,7 +750,14 @@
     return false;
   }
   std::locale c_locale("C");
-  if (!std::isalpha(str[0], c_locale)) {
+  if (str[0] == '_') {
+    if (str.length() == 1u || str[1] == '_') {
+      // https://www.w3.org/TR/WGSL/#identifiers
+      // must not be '_' (a single underscore)
+      // must not start with two underscores
+      return false;
+    }
+  } else if (!std::isalpha(str[0], c_locale)) {
     return false;
   }
   for (const char& ch : str) {
diff --git a/src/reader/spirv/parser_impl_test.cc b/src/reader/spirv/parser_impl_test.cc
index 72c8446..49ccad3 100644
--- a/src/reader/spirv/parser_impl_test.cc
+++ b/src/reader/spirv/parser_impl_test.cc
@@ -202,8 +202,9 @@
 
 TEST_F(SpvParserTest, Impl_IsValidIdentifier) {
   EXPECT_FALSE(ParserImpl::IsValidIdentifier(""));  // empty
-  EXPECT_FALSE(
-      ParserImpl::IsValidIdentifier("_"));  // leading underscore, but ok later
+  EXPECT_FALSE(ParserImpl::IsValidIdentifier("_"));
+  EXPECT_FALSE(ParserImpl::IsValidIdentifier("__"));
+  EXPECT_TRUE(ParserImpl::IsValidIdentifier("_x"));
   EXPECT_FALSE(
       ParserImpl::IsValidIdentifier("9"));  // leading digit, but ok later
   EXPECT_FALSE(ParserImpl::IsValidIdentifier(" "));    // leading space