Trim labels in location expressions before expansion.

--
Change-Id: If626fd448ddbfbdf65b71569fda7a9b206e5f8b2
Reviewed-on: https://bazel-review.googlesource.com/c/6890/
MOS_MIGRATED_REVID=137155361
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java b/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
index 882b93b..225b3e1 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
@@ -48,7 +48,7 @@
  * Note that //mypackage:myhelper should have just one output.
  */
 public class LocationExpander {
-  
+
   /**
    * List of options to tweak the LocationExpander.
    */
@@ -58,7 +58,7 @@
     /** Allow to take label from the data attribute */
     ALLOW_DATA,
   }
-  
+
   private static final int MAX_PATHS_SHOWN = 5;
   private static final String LOCATION = "$(location";
   private final RuleContext ruleContext;
@@ -105,7 +105,7 @@
 
   /**
    * Creates location expander helper bound to specific target.
-   * 
+   *
    * @param ruleContext the BUILD rule's context
    * @param options the list of options, see {@link Options}.
    */
@@ -181,7 +181,7 @@
       message = String.format(" in %s expression", message);
 
       // (2) parse label
-      String labelText = value.substring(start + scannedLength, end);
+      String labelText = value.substring(start + scannedLength, end).trim();
       Label label = parseLabel(labelText, message, reporter);
 
       if (label == null) {
@@ -206,7 +206,7 @@
 
       restart = end + 1;
     }
-    
+
     return result.toString();
   }
 
@@ -357,7 +357,7 @@
     }
     return values;
   }
-  
+
   private static interface ErrorReporter {
     void report(RuleContext ctx, String error);
   }
diff --git a/src/test/shell/bazel/location_test.sh b/src/test/shell/bazel/location_test.sh
index 2435dcc..801aa19 100755
--- a/src/test/shell/bazel/location_test.sh
+++ b/src/test/shell/bazel/location_test.sh
@@ -75,4 +75,24 @@
   assert_contains "hello" bazel-genfiles/bar/loc
 }
 
+function test_location_trim() {
+  mkdir bar
+  cat > bar/BUILD <<EOF
+genrule(
+    name = "baz-rule",
+    outs = ["baz"],
+    cmd = "echo helloworld > \"\$@\"",
+)
+
+genrule(
+    name = "loc-rule",
+    srcs = [":baz-rule"],
+    outs = ["loc"],
+    cmd = "echo \$(location  :baz-rule ) > \"\$@\"",
+)
+EOF
+
+  bazel build //bar:loc || fail "Label was not trimmed before lookup"
+}
+
 run_suite "location tests"