Throw QueryException if TargetLiteral fails validation during parsing.

By not throwing an IllegalArgumentException in this case we avoid crashing blaze
itself when given a target name beginning with a hyphen (-).

RELNOTES: none
PiperOrigin-RevId: 250278700
diff --git a/src/main/java/com/google/devtools/build/lib/query2/engine/QueryParser.java b/src/main/java/com/google/devtools/build/lib/query2/engine/QueryParser.java
index 64dd0e6..4301008 100644
--- a/src/main/java/com/google/devtools/build/lib/query2/engine/QueryParser.java
+++ b/src/main/java/com/google/devtools/build/lib/query2/engine/QueryParser.java
@@ -227,7 +227,7 @@
           consume(TokenKind.RPAREN);
           return new FunctionExpression(function, args);
         } else {
-          return new TargetLiteral(word);
+            return validateTargetLiteral(word);
         }
       }
       case LET: {
@@ -250,7 +250,7 @@
         consume(TokenKind.LPAREN);
         List<TargetLiteral> words = new ArrayList<>();
         while (token.kind == TokenKind.WORD) {
-          words.add(new TargetLiteral(consume(TokenKind.WORD)));
+            words.add(validateTargetLiteral(consume(TokenKind.WORD)));
         }
         consume(TokenKind.RPAREN);
         return new SetExpression(words);
@@ -259,4 +259,11 @@
         throw syntaxError(token);
     }
   }
+
+  private static TargetLiteral validateTargetLiteral(String word) throws QueryException {
+    if (word.startsWith("-")) {
+      throw new QueryException("target literal must not begin with hyphen (-): " + word);
+    }
+    return new TargetLiteral(word);
+  }
 }
diff --git a/src/main/java/com/google/devtools/build/lib/query2/engine/TargetLiteral.java b/src/main/java/com/google/devtools/build/lib/query2/engine/TargetLiteral.java
index fe669e0..6f99765 100644
--- a/src/main/java/com/google/devtools/build/lib/query2/engine/TargetLiteral.java
+++ b/src/main/java/com/google/devtools/build/lib/query2/engine/TargetLiteral.java
@@ -34,7 +34,6 @@
 
   public TargetLiteral(String pattern) {
     this.pattern = Preconditions.checkNotNull(pattern);
-    Preconditions.checkArgument(!pattern.startsWith("-"));
   }
 
   public String getPattern() {
diff --git a/src/test/shell/integration/bazel_query_test.sh b/src/test/shell/integration/bazel_query_test.sh
index 991bad5..f9eda24 100755
--- a/src/test/shell/integration/bazel_query_test.sh
+++ b/src/test/shell/integration/bazel_query_test.sh
@@ -89,6 +89,12 @@
   expect_log "//peach:harken"
 }
 
+function test_invalid_query_fails_parsing() {
+  bazel query 'deps("--bad_target_name_from_bad_script")' >& "$TEST_log" \
+    && fail "Expected failure"
+  expect_log "target literal must not begin with hyphen"
+}
+
 function test_visibility_affects_xml_output() {
   rm -rf kiwi
   mkdir -p kiwi
@@ -546,4 +552,4 @@
   expect_log "$expected_error_msg"
 }
 
-run_suite "${PRODUCT_NAME} query tests"
\ No newline at end of file
+run_suite "${PRODUCT_NAME} query tests"