Skip to content

Commit

Permalink
AttributeSet type
Browse files Browse the repository at this point in the history
  • Loading branch information
neunenak committed Oct 31, 2024
1 parent 528c9f0 commit 73a6f51
Show file tree
Hide file tree
Showing 7 changed files with 229 additions and 117 deletions.
4 changes: 2 additions & 2 deletions src/alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use super::*;
/// An alias, e.g. `name := target`
#[derive(Debug, PartialEq, Clone, Serialize)]
pub(crate) struct Alias<'src, T = Rc<Recipe<'src>>> {
pub(crate) attributes: BTreeSet<Attribute<'src>>,
pub(crate) attributes: AttributeSet<'src>,
pub(crate) name: Name<'src>,
#[serde(
bound(serialize = "T: Keyed<'src>"),
Expand All @@ -26,7 +26,7 @@ impl<'src> Alias<'src, Name<'src>> {

impl Alias<'_> {
pub(crate) fn is_private(&self) -> bool {
self.name.lexeme().starts_with('_') || self.attributes.contains(&Attribute::Private)
self.name.lexeme().starts_with('_') || self.attributes.private()
}
}

Expand Down
43 changes: 16 additions & 27 deletions src/analyzer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,17 @@ impl<'run, 'src> Analyzer<'run, 'src> {
} => {
let mut doc_attr: Option<&str> = None;
let mut groups = Vec::new();
for attribute in attributes {
attributes.ensure_valid_attributes(
"Module",
**name,
&[AttributeDiscriminant::Doc, AttributeDiscriminant::Group],
)?;

for attribute in attributes.iter() {
if let Attribute::Doc(ref doc) = attribute {
doc_attr = Some(doc.as_ref().map(|s| s.cooked.as_ref()).unwrap_or_default());
} else if let Attribute::Group(ref group) = attribute {
groups.push(group.cooked.clone());
} else {
return Err(name.token.error(InvalidAttribute {
item_kind: "Module",
item_name: name.lexeme(),
attribute: attribute.clone(),
}));
}
}

Expand Down Expand Up @@ -169,11 +169,9 @@ impl<'run, 'src> Analyzer<'run, 'src> {
let mut unstable_features = BTreeSet::new();

for recipe in recipes.values() {
for attribute in &recipe.attributes {
if let Attribute::Script(_) = attribute {
unstable_features.insert(UnstableFeature::ScriptAttribute);
break;
}
if recipe.attributes.contains(AttributeDiscriminant::Script) {
unstable_features.insert(UnstableFeature::ScriptAttribute);
break;
}
}

Expand Down Expand Up @@ -283,11 +281,7 @@ impl<'run, 'src> Analyzer<'run, 'src> {
}

if !recipe.is_script() {
if let Some(attribute) = recipe
.attributes
.iter()
.find(|attribute| matches!(attribute, Attribute::Extension(_)))
{
if let Some(attribute) = recipe.attributes.get(AttributeDiscriminant::Extension) {
return Err(recipe.name.error(InvalidAttribute {
item_kind: "Recipe",
item_name: recipe.name.lexeme(),
Expand All @@ -300,16 +294,11 @@ impl<'run, 'src> Analyzer<'run, 'src> {
}

fn analyze_alias(alias: &Alias<'src, Name<'src>>) -> CompileResult<'src> {
for attribute in &alias.attributes {
if *attribute != Attribute::Private {
return Err(alias.name.token.error(InvalidAttribute {
item_kind: "Alias",
item_name: alias.name.lexeme(),
attribute: attribute.clone(),
}));
}
}

alias.attributes.ensure_valid_attributes(
"Alias",
*alias.name,
&[AttributeDiscriminant::Private],
)?;
Ok(())
}

Expand Down
67 changes: 67 additions & 0 deletions src/attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,73 @@ impl<'src> Display for Attribute<'src> {
}
}

#[derive(Default, Debug, Clone, PartialEq)]
pub(crate) struct AttributeSet<'src> {
inner: BTreeSet<Attribute<'src>>,
}

impl<'src> Serialize for AttributeSet<'src> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.inner.serialize(serializer)
}
}

impl<'src> AttributeSet<'src> {
pub(crate) fn from_iter(iter: impl IntoIterator<Item = Attribute<'src>>) -> Self {
Self {
inner: iter.into_iter().collect(),
}
}

pub(crate) fn count(&self) -> usize {
self.inner.len()
}

pub(crate) fn contains(&self, target: AttributeDiscriminant) -> bool {
self.inner.iter().any(|attr| {
let discriminant: AttributeDiscriminant = attr.into();
discriminant == target
})
}

pub(crate) fn get(&self, discriminant: AttributeDiscriminant) -> Option<&Attribute<'src>> {
self.inner.iter().find(|attr| {
let item_discriminant: AttributeDiscriminant = (*attr).into();
discriminant == item_discriminant
})
}

pub(crate) fn iter(&self) -> impl Iterator<Item = &Attribute<'src>> {
self.inner.iter()
}

pub(crate) fn private(&self) -> bool {
self.inner.contains(&Attribute::Private)
}

pub(crate) fn ensure_valid_attributes(
&self,
item_kind: &'static str,
item_token: Token<'src>,
valid: &[AttributeDiscriminant],
) -> Result<(), CompileError<'src>> {
for attribute in &self.inner {
let discriminant: AttributeDiscriminant = attribute.into();
if !valid.contains(&discriminant) {
return Err(item_token.error(CompileErrorKind::InvalidAttribute {
item_kind,
item_name: item_token.lexeme(),
attribute: attribute.clone(),
}));
}
}
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
2 changes: 1 addition & 1 deletion src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub(crate) enum Item<'src> {
relative: StringLiteral<'src>,
},
Module {
attributes: BTreeSet<Attribute<'src>>,
attributes: AttributeSet<'src>,
absolute: Option<PathBuf>,
doc: Option<&'src str>,
name: Name<'src>,
Expand Down
114 changes: 89 additions & 25 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,95 @@
pub(crate) use {
crate::{
alias::Alias, analyzer::Analyzer, argument_parser::ArgumentParser, assignment::Assignment,
assignment_resolver::AssignmentResolver, ast::Ast, attribute::Attribute, binding::Binding,
color::Color, color_display::ColorDisplay, command_color::CommandColor,
command_ext::CommandExt, compilation::Compilation, compile_error::CompileError,
compile_error_kind::CompileErrorKind, compiler::Compiler, condition::Condition,
conditional_operator::ConditionalOperator, config::Config, config_error::ConfigError,
constants::constants, count::Count, delimiter::Delimiter, dependency::Dependency,
dump_format::DumpFormat, enclosure::Enclosure, error::Error, evaluator::Evaluator,
execution_context::ExecutionContext, executor::Executor, expression::Expression,
fragment::Fragment, function::Function, interpreter::Interpreter,
interrupt_guard::InterruptGuard, interrupt_handler::InterruptHandler, item::Item,
justfile::Justfile, keyed::Keyed, keyword::Keyword, lexer::Lexer, line::Line, list::List,
load_dotenv::load_dotenv, loader::Loader, module_path::ModulePath, name::Name,
namepath::Namepath, ordinal::Ordinal, output::output, output_error::OutputError,
parameter::Parameter, parameter_kind::ParameterKind, parser::Parser, platform::Platform,
platform_interface::PlatformInterface, position::Position, positional::Positional, ran::Ran,
range_ext::RangeExt, recipe::Recipe, recipe_resolver::RecipeResolver,
recipe_signature::RecipeSignature, scope::Scope, search::Search, search_config::SearchConfig,
search_error::SearchError, set::Set, setting::Setting, settings::Settings, shebang::Shebang,
show_whitespace::ShowWhitespace, source::Source, string_delimiter::StringDelimiter,
string_kind::StringKind, string_literal::StringLiteral, subcommand::Subcommand,
suggestion::Suggestion, table::Table, thunk::Thunk, token::Token, token_kind::TokenKind,
unresolved_dependency::UnresolvedDependency, unresolved_recipe::UnresolvedRecipe,
unstable_feature::UnstableFeature, use_color::UseColor, variables::Variables,
verbosity::Verbosity, warning::Warning,
alias::Alias,
analyzer::Analyzer,
argument_parser::ArgumentParser,
assignment::Assignment,
assignment_resolver::AssignmentResolver,
ast::Ast,
attribute::{Attribute, AttributeDiscriminant, AttributeSet},
binding::Binding,
color::Color,
color_display::ColorDisplay,
command_color::CommandColor,
command_ext::CommandExt,
compilation::Compilation,
compile_error::CompileError,
compile_error_kind::CompileErrorKind,
compiler::Compiler,
condition::Condition,
conditional_operator::ConditionalOperator,
config::Config,
config_error::ConfigError,
constants::constants,
count::Count,
delimiter::Delimiter,
dependency::Dependency,
dump_format::DumpFormat,
enclosure::Enclosure,
error::Error,
evaluator::Evaluator,
execution_context::ExecutionContext,
executor::Executor,
expression::Expression,
fragment::Fragment,
function::Function,
interpreter::Interpreter,
interrupt_guard::InterruptGuard,
interrupt_handler::InterruptHandler,
item::Item,
justfile::Justfile,
keyed::Keyed,
keyword::Keyword,
lexer::Lexer,
line::Line,
list::List,
load_dotenv::load_dotenv,
loader::Loader,
module_path::ModulePath,
name::Name,
namepath::Namepath,
ordinal::Ordinal,
output::output,
output_error::OutputError,
parameter::Parameter,
parameter_kind::ParameterKind,
parser::Parser,
platform::Platform,
platform_interface::PlatformInterface,
position::Position,
positional::Positional,
ran::Ran,
range_ext::RangeExt,
recipe::Recipe,
recipe_resolver::RecipeResolver,
recipe_signature::RecipeSignature,
scope::Scope,
search::Search,
search_config::SearchConfig,
search_error::SearchError,
set::Set,
setting::Setting,
settings::Settings,
shebang::Shebang,
show_whitespace::ShowWhitespace,
source::Source,
string_delimiter::StringDelimiter,
string_kind::StringKind,
string_literal::StringLiteral,
subcommand::Subcommand,
suggestion::Suggestion,
table::Table,
thunk::Thunk,
token::Token,
token_kind::TokenKind,
unresolved_dependency::UnresolvedDependency,
unresolved_recipe::UnresolvedRecipe,
unstable_feature::UnstableFeature,
use_color::UseColor,
variables::Variables,
verbosity::Verbosity,
warning::Warning,
},
camino::Utf8Path,
clap::ValueEnum,
Expand Down
34 changes: 11 additions & 23 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ impl<'run, 'src> Parser<'run, 'src> {

if let Some((token, attributes)) = attributes {
return Err(token.error(CompileErrorKind::ExtraneousAttributes {
count: attributes.len(),
count: attributes.count(),
}));
}
}
Expand All @@ -459,7 +459,7 @@ impl<'run, 'src> Parser<'run, 'src> {
/// Parse an alias, e.g `alias name := target`
fn parse_alias(
&mut self,
attributes: BTreeSet<Attribute<'src>>,
attributes: AttributeSet<'src>,
) -> CompileResult<'src, Alias<'src, Name<'src>>> {
self.presume_keyword(Keyword::Alias)?;
let name = self.parse_name()?;
Expand All @@ -477,24 +477,15 @@ impl<'run, 'src> Parser<'run, 'src> {
fn parse_assignment(
&mut self,
export: bool,
attributes: BTreeSet<Attribute<'src>>,
attributes: AttributeSet<'src>,
) -> CompileResult<'src, Assignment<'src>> {
let name = self.parse_name()?;
self.presume(ColonEquals)?;
let value = self.parse_expression()?;
self.expect_eol()?;

let private = attributes.contains(&Attribute::Private);

for attribute in attributes {
if attribute != Attribute::Private {
return Err(name.error(CompileErrorKind::InvalidAttribute {
item_kind: "Assignment",
item_name: name.lexeme(),
attribute,
}));
}
}
let private = attributes.private();
attributes.ensure_valid_attributes("Assignment", *name, &[AttributeDiscriminant::Private])?;

Ok(Assignment {
file_depth: self.file_depth,
Expand Down Expand Up @@ -827,7 +818,7 @@ impl<'run, 'src> Parser<'run, 'src> {
&mut self,
doc: Option<&'src str>,
quiet: bool,
attributes: BTreeSet<Attribute<'src>>,
attributes: AttributeSet<'src>,
) -> CompileResult<'src, UnresolvedRecipe<'src>> {
let name = self.parse_name()?;

Expand Down Expand Up @@ -888,17 +879,15 @@ impl<'run, 'src> Parser<'run, 'src> {
let body = self.parse_body()?;

let shebang = body.first().map_or(false, Line::is_shebang);
let script = attributes
.iter()
.any(|attribute| matches!(attribute, Attribute::Script(_)));
let script = attributes.contains(AttributeDiscriminant::Script);

if shebang && script {
return Err(name.error(CompileErrorKind::ShebangAndScriptAttribute {
recipe: name.lexeme(),
}));
}

let private = name.lexeme().starts_with('_') || attributes.contains(&Attribute::Private);
let private = name.lexeme().starts_with('_') || attributes.private();

Ok(Recipe {
shebang: shebang || script,
Expand Down Expand Up @@ -1078,9 +1067,7 @@ impl<'run, 'src> Parser<'run, 'src> {
}

/// Item attributes, i.e., `[macos]` or `[confirm: "warning!"]`
fn parse_attributes(
&mut self,
) -> CompileResult<'src, Option<(Token<'src>, BTreeSet<Attribute<'src>>)>> {
fn parse_attributes(&mut self) -> CompileResult<'src, Option<(Token<'src>, AttributeSet<'src>)>> {
let mut attributes = BTreeMap::new();

let mut token = None;
Expand Down Expand Up @@ -1128,7 +1115,8 @@ impl<'run, 'src> Parser<'run, 'src> {
if attributes.is_empty() {
Ok(None)
} else {
Ok(Some((token.unwrap(), attributes.into_keys().collect())))
let attribute_set = AttributeSet::from_iter(attributes.into_keys());
Ok(Some((token.unwrap(), attribute_set)))
}
}
}
Expand Down
Loading

0 comments on commit 73a6f51

Please sign in to comment.