blob: d61935295a96bc27fc39db491865d3e302461773 [file] [edit]
// Copyright 2026 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Bazel label parsing for `bazel::import!`.
/// A validated absolute main-repository Bazel label (`//package[:target]`,
/// `//:target`).
#[derive(Debug, PartialEq, Eq)]
pub struct Label<'a> {
raw: &'a str,
target: &'a str,
}
impl<'a> Label<'a> {
/// Parses and validates an absolute main-repository Bazel label.
///
/// Accepts `//package[:target]` and `//:target`. Validation follows
/// Bazel's `LabelValidator` rules without requiring the target name to be a
/// valid Rust identifier (call [`Self::crate_name`] to derive and validate
/// the default crate name).
pub fn parse(label: &'a str) -> Result<Self, String> {
let Some(rest) = label.strip_prefix("//") else {
return Err(format!(
"invalid Bazel label `{label}`: labels must be absolute (start with `//`)"
));
};
let (package, target) = match rest.split_once(':') {
Some((package, target)) => (package, target),
None => {
if rest.is_empty() {
return Err(format!(
"invalid Bazel label `{label}`: missing package or target"
));
}
let implicit = rest.rsplit('/').next().unwrap_or("");
(rest, implicit)
}
};
validate_package_name(label, package)?;
validate_target_name(label, target)?;
Ok(Self { raw: label, target })
}
/// Derives the default Rust crate name from the label's target name.
///
/// Dashes and slashes in target names are normalized to underscores,
/// matching `rules_rust`.
pub fn crate_name(&self) -> Result<String, String> {
let crate_name: String = self
.target
.chars()
.map(|c| match c {
'-' | '/' => '_',
other => other,
})
.collect();
if !is_valid_crate_identifier(&crate_name) {
return Err(format!(
"invalid Bazel label `{}`: derived crate name `{crate_name}` is not a valid Rust identifier",
self.raw
));
}
Ok(crate_name)
}
}
fn validate_package_name(label: &str, package: &str) -> Result<(), String> {
if package.is_empty() {
return Ok(());
}
if !package.bytes().all(|b| matches!(b, b' '..=b'~') && b != b'\\') {
return Err(format!("invalid Bazel label `{label}`: invalid character in package name"));
}
for segment in package.split('/') {
if segment.is_empty() || segment.bytes().all(|b| b == b'.') {
return Err(format!(
"invalid Bazel label `{label}`: invalid package segment `{segment}`"
));
}
}
Ok(())
}
fn validate_target_name(label: &str, target: &str) -> Result<(), String> {
if target.is_empty()
|| target.contains(':')
|| target.bytes().any(|b| b < b' ' || b == 0x7f || b == b'\\')
|| target.split('/').any(|segment| segment.is_empty() || matches!(segment, "." | ".."))
{
return Err(format!("invalid Bazel label `{label}`: invalid target name"));
}
Ok(())
}
fn is_valid_crate_identifier(s: &str) -> bool {
match s.as_bytes() {
[] | [b'_'] => false,
[first, rest @ ..] => {
(first.is_ascii_alphabetic() || *first == b'_')
&& rest.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'_')
}
}
}