Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions crates/solverforge-macros/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,9 @@ runtime scalar surface is candidate-index based.
**Generated code:**
- `impl PlanningEntity for T` — `is_pinned()`, `as_any()`, `as_any_mut()`
- `impl PlanningId for T` (if `#[planning_id]` present) — `type Id` set to field type, `planning_id()` returns field value
- `impl T { pub fn entity_descriptor(solution_field: &'static str) -> EntityDescriptor }` — builds descriptor with all variable descriptors (genuine, list, shadow) and preserves `#[planning_id]` metadata; `#[planning_pin]` supplies both the pin field name and a typed predicate that calls `PlanningEntity::is_pinned()`
- `impl T { #[doc(hidden)] pub fn entity_descriptor(solution_field: &'static str) -> EntityDescriptor }` — builds descriptor with all variable descriptors (genuine, list, shadow) and preserves `#[planning_id]` metadata; `#[planning_pin]` supplies both the pin field name and a typed predicate that calls `PlanningEntity::is_pinned()`
- Hidden scalar metadata bridge: private indexed helpers for scalar variable count, name, allows-unassigned, value-source metadata, getter/setter, and entity-local value slices. Helper order matches `entity_descriptor()` genuine scalar variable order; the index is used for generated getter/setter dispatch, while manifest hook attachment resolves descriptor variables by descriptor index plus variable name.
- Hidden list metadata bridge (when the entity has a `#[planning_list_variable]` field): public cross-module `__SOLVERFORGE_LIST_VARIABLE_COUNT` plus private `__SOLVERFORGE_LIST_VARIABLE_NAME`, `__SOLVERFORGE_LIST_ELEMENT_COLLECTION`, `__solverforge_list_field()`, `__solverforge_list_field_mut()`, `__solverforge_list_metadata()`
- Hidden list metadata bridge (when the entity has a `#[planning_list_variable]` field): public cross-module `#[doc(hidden)]` `__SOLVERFORGE_LIST_VARIABLE_COUNT` (also emitted as `0` for entities without a list variable) plus private `__SOLVERFORGE_LIST_VARIABLE_NAME`, `__SOLVERFORGE_LIST_ELEMENT_COLLECTION`, `__solverforge_list_field()`, `__solverforge_list_field_mut()`, `__solverforge_list_metadata()`
- Hidden list metadata bridge implementation (when the entity has a `#[planning_list_variable]` field): `impl __internal::ListVariableEntity<Solution> for Entity`
- Unassigned bridge (when the entity has exactly one `Option<_>` planning variable): `impl __internal::UnassignedEntity<Solution> for Entity`, the public `stream::UnassignedEntity`, enabling `.unassigned()` on `UniConstraintStream<_, Entity, ...>` without a generated public trait import

Expand Down Expand Up @@ -261,16 +261,16 @@ semantics should omit `domain = "cvrp"` and declare explicit hook paths instead.

**Generated code:**
- `impl PlanningSolution for T` — `type Score`, `score()`, `set_score()`, `HAS_CONSTRAINT_WEIGHTS = true` plus `constraint_weights()` returning `Some(&self.field)` when a `#[constraint_weights]` field exists (otherwise both keep their unweighted defaults), plus `update_entity_shadows()` / `update_all_shadows()` / `list_shadow_elements()` / `clear_list_shadows()` / `list_shadow_source()` delegation to the manifest-owned support implementation when `#[shadow_variable_updates(...)]` configures list shadows.
- `impl T { pub fn descriptor() -> SolutionDescriptor }` — builds full descriptor with entity extractors and fact extractors, reusing entity-generated descriptors so field-level variable order and metadata are preserved
- `impl T { pub fn entity_count(&Self, descriptor_index: usize) -> usize }` — entity count by descriptor index
- `impl T { #[doc(hidden)] pub fn descriptor() -> SolutionDescriptor }` — builds full descriptor with entity extractors and fact extractors, reusing entity-generated descriptors so field-level variable order and metadata are preserved
- `impl T { #[doc(hidden)] pub fn entity_count(&Self, descriptor_index: usize) -> usize }` — entity count by descriptor index
- Private owner-specific list operations used by the canonical runtime: `__solverforge_list_len_<owner>()`, `__solverforge_list_remove_<owner>()`, `__solverforge_list_insert_<owner>()`, `__solverforge_list_get_<owner>()`, `__solverforge_list_set_<owner>()`, `__solverforge_list_reverse_<owner>()`, `__solverforge_sublist_remove_<owner>()`, `__solverforge_sublist_insert_<owner>()`, `__solverforge_ruin_remove_<owner>()`, `__solverforge_ruin_insert_<owner>()`, `__solverforge_index_to_element_<owner>()`, `__solverforge_element_source_key_<owner>()`, `__solverforge_element_count_<owner>()`, `__solverforge_assigned_elements_<owner>()`, `__solverforge_n_entities_<owner>()`, `__solverforge_assign_element_<owner>()`, plus aggregate helpers `__solverforge_total_list_entities()` and `__solverforge_total_list_elements()`
- `impl SolvableSolution for T` — delegates to `descriptor()` and `entity_count()`
- `impl Solvable for T` (when constraints path specified) — `solve(self, runtime: SolverRuntime<Self>, qualified_candidate_trace_provenance: Option<QualifiedCandidateTraceRunProvenance>) -> RuntimeBuildResult<()>` delegates to `solve_internal()` and returns its error instead of panicking
- `impl Analyzable for T` (when constraints path specified) — `analyze()` creates `ScoreDirector` (a `WeightedMode` director when a `#[constraint_weights]` field exists) with canonical shadow support and returns `ScoreAnalysis` with weighted scores and each constraint's `weight_multiplier`; it panics with the `ConstraintWeightError` message when the solution's weights name an unknown constraint or exceed the cap
- `impl T { pub fn validate_constraint_weights(&ConstraintWeights) -> Result<(), ConstraintWeightError> }` (when constraints path specified) — builds the constraint set once and runs the same checks a solve runs at start, so callers can reject a typo before submitting
- `pub fn solve_with_config(self, config: SolverConfig) -> RuntimeBuildResult<Self>` (when constraints path specified) — solves on the calling thread with exactly `config` (neither `solver_toml` nor the `config` callback is applied) through a detached `SolverRuntime`, returning the best solution or the build error
- `fn solve_internal(self, runtime: SolverRuntime<Self>, qualified_candidate_trace_provenance: Option<QualifiedCandidateTraceRunProvenance>) -> RuntimeBuildResult<Self>` (when constraints path specified) — starts from the embedded `solver_toml` config (parsed once; a parse error returns `RuntimeBuildError::Configuration` with the error's `Display` text) or `SolverConfig::default()` without reading the working directory, applies the optional `config = "..."` callback, and calls hidden `try_run_solver_with_config_and_search` — or hidden `try_run_weighted_solver_with_config_and_search` when a `#[constraint_weights]` field exists, so only weighted models ever instantiate the weighted solver — passing the constraints function as the constraint-set constructor (`fn(&Self) -> _`) used for the working solution and every evaluator replica. The generated `__solverforge_search_declaration(config, descriptor)` builds one `RuntimeModel` containing scalar slots plus zero or more owner-specific list slots, delegates scalar hook and scalar-group attachment to the `planning_model!` support impl, sorts those variable slots to the descriptor-backed variable order emitted by the macros, constructs `SearchContext` with the fallible `SearchContext::new`, and returns the selected custom `Search` declaration or canonical defaults. The compiled runtime owns phase preparation, source binding, construction, local search, and terminal lifecycle; no macro-generated phase sequence exists.
- Public solution source methods for all `#[planning_entity_collection]`, `#[problem_fact_collection]`, and streamable `#[planning_list_element_collection]` fields. Each method is inherent on the solution type, for example `Plan::tasks()`, returns the concrete hidden `SourceExtract<fn(&Plan) -> &[Task]>` wrapper, and carries hidden `ChangeSource::Descriptor(idx)` for planning entities or `ChangeSource::Static` for facts and list elements. User constraints can call the explicit form `ConstraintFactory::new().for_each(Plan::tasks())` or import the generated `PlanConstraintStreams` trait and call `ConstraintFactory::new().tasks()`. Both paths use the same source metadata and concrete stream types.
- Public solution source methods for all `#[planning_entity_collection]`, `#[problem_fact_collection]`, and streamable `#[planning_list_element_collection]` fields. Each method is inherent on the solution type, for example `Plan::tasks()`, returns the concrete hidden `SourceExtract<fn(&Plan) -> &[Task]>` wrapper, and carries hidden `ChangeSource::Descriptor(idx)` for planning entities or `ChangeSource::Static` for facts and list elements. User constraints can call the explicit form `ConstraintFactory::new().for_each(Plan::tasks())` or import the generated `PlanConstraintStreams` trait and call `ConstraintFactory::new().tasks()`. Both paths use the same source metadata and concrete stream types. The source methods, the trait and its methods carry generated docs, and the plumbing above is `#[doc(hidden)]`, so a user crate that enables `missing_docs` gets no warnings from generated items.

### Problem Fact Support Derive

Expand All @@ -280,7 +280,7 @@ semantics should omit `domain = "cvrp"` and declare explicit hook paths instead.
**Generated code:**
- `impl ProblemFact for T` — `as_any()`
- `impl PlanningId for T` (if `#[planning_id]` present) — same as entity version
- `impl T { pub fn problem_fact_descriptor(solution_field: &'static str) -> ProblemFactDescriptor }`
- `impl T { #[doc(hidden)] pub fn problem_fact_descriptor(solution_field: &'static str) -> ProblemFactDescriptor }`

## Shared Helper Functions (`entrypoints.rs` / `attr_parse.rs` / `attr_validation.rs`, private)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,7 @@ pub(crate) fn expand_derive(input: DeriveInput) -> Result<TokenStream, Error> {
#scalar_helpers
#list_metadata

#[doc(hidden)]
pub fn entity_descriptor(solution_field: &'static str) -> ::solverforge::__internal::EntityDescriptor {
let mut desc = ::solverforge::__internal::EntityDescriptor::new(
#name_str,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub(super) fn generate_list_metadata(
) -> Result<TokenStream, Error> {
let Some(field) = list_variables.first().copied() else {
return Ok(quote! {
#[doc(hidden)]
pub const __SOLVERFORGE_LIST_VARIABLE_COUNT: usize = 0;
});
};
Expand Down Expand Up @@ -118,6 +119,7 @@ pub(super) fn generate_list_metadata(
(quote! {}, quote! { ::core::option::Option::None })
};
Ok(quote! {
#[doc(hidden)]
pub const __SOLVERFORGE_LIST_VARIABLE_COUNT: usize = 1;
const __SOLVERFORGE_LIST_VARIABLE_NAME: &'static str = #field_name_str;
const __SOLVERFORGE_LIST_ELEMENT_COLLECTION: &'static str = #element_collection;
Expand Down
2 changes: 2 additions & 0 deletions crates/solverforge-macros/src/planning_solution/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ pub(crate) fn expand_derive(input: DeriveInput) -> Result<TokenStream, Error> {
}

impl #impl_generics #name #ty_generics #where_clause {
#[doc(hidden)]
pub fn descriptor() -> ::solverforge::__internal::SolutionDescriptor {
let mut descriptor = ::solverforge::__internal::SolutionDescriptor::new(
#name_str,
Expand All @@ -218,6 +219,7 @@ pub(crate) fn expand_derive(input: DeriveInput) -> Result<TokenStream, Error> {
descriptor
}

#[doc(hidden)]
#[inline]
pub fn entity_count(this: &Self, descriptor_index: usize) -> usize {
match descriptor_index {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub(super) fn generate_collection_source_methods(
let descriptor_index_lit = syn::Index::from(descriptor_index);

source_methods.push(quote! {
#[doc = concat!("Constraint-stream source over the `", stringify!(#field_name), "` collection.")]
pub fn #field_name() -> ::solverforge::__internal::SourceExtract<fn(&Self) -> &[#element_type]> {
::solverforge::__internal::source(
(|s: &Self| s.#field_name.as_slice()) as fn(&Self) -> &[#element_type],
Expand All @@ -58,6 +59,7 @@ pub(super) fn generate_collection_source_methods(

let change_source = unowned_change_source(&quote! { Self }, field_name);
source_methods.push(quote! {
#[doc = concat!("Constraint-stream source over the `", stringify!(#field_name), "` collection.")]
pub fn #field_name() -> ::solverforge::__internal::SourceExtract<fn(&Self) -> &[#element_type]> {
::solverforge::__internal::source(
(|s: &Self| s.#field_name.as_slice()) as fn(&Self) -> &[#element_type],
Expand All @@ -79,6 +81,7 @@ pub(super) fn generate_collection_source_methods(

let change_source = unowned_change_source(&quote! { Self }, field_name);
source_methods.push(quote! {
#[doc = concat!("Constraint-stream source over the `", stringify!(#field_name), "` collection.")]
pub fn #field_name() -> ::solverforge::__internal::SourceExtract<fn(&Self) -> &[#element_type]> {
::solverforge::__internal::source(
(|s: &Self| s.#field_name.as_slice()) as fn(&Self) -> &[#element_type],
Expand Down Expand Up @@ -161,6 +164,7 @@ pub(super) fn generate_constraint_stream_extensions(
}

quote! {
#[doc = concat!("Constraint-stream entry points for each `", stringify!(#solution_name), "` collection.")]
pub trait #trait_name<Sc: ::solverforge::Score + 'static> {
#(#trait_methods)*
}
Expand Down Expand Up @@ -192,6 +196,7 @@ fn push_stream_extension_method(
};

trait_methods.push(quote! {
#[doc = concat!("Streams every row of the `", stringify!(#field_name), "` collection.")]
fn #field_name(self) -> #return_type;
});

Expand Down
1 change: 1 addition & 0 deletions crates/solverforge-macros/src/problem_fact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ pub fn expand_derive(input: DeriveInput) -> Result<TokenStream, Error> {
#planning_id_impl

impl #impl_generics #name #ty_generics #where_clause {
#[doc(hidden)]
pub fn problem_fact_descriptor(
solution_field: &'static str,
) -> ::solverforge::__internal::ProblemFactDescriptor {
Expand Down
16 changes: 16 additions & 0 deletions crates/solverforge/tests/generated_items_documented.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//! The planning macros document or hide every public item they generate, so a
//! crate that denies `missing_docs` compiles with them.
#![deny(missing_docs)]

#[path = "generated_items_documented/mod.rs"]
mod domain;

pub use domain::{Plan, PlanConstraintStreams, Route, Visit};

#[test]
fn documented_model_exposes_its_collection_sources() {
let descriptor = Plan::descriptor();
assert!(descriptor.find_entity_descriptor("Route").is_some());
let _routes = Plan::routes();
let _visits = Plan::visits();
}
12 changes: 12 additions & 0 deletions crates/solverforge/tests/generated_items_documented/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
solverforge::planning_model! {
root = "crates/solverforge/tests/generated_items_documented";

mod plan;
mod route;
mod visit;

pub use plan::Plan;
pub use plan::PlanConstraintStreams;
pub use route::Route;
pub use visit::Visit;
}
31 changes: 31 additions & 0 deletions crates/solverforge/tests/generated_items_documented/plan.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use solverforge::prelude::*;
use solverforge::stream::ConstraintFactory;

use crate::{Route, Visit};

/// A plan with one list-and-scalar entity collection and one fact collection.
#[planning_solution(
constraints = "constraints",
solver_toml = "../fixtures/mixed_variable_order_runtime_solver.toml"
)]
pub struct Plan {
/// Routes the solver plans.
#[planning_entity_collection]
pub routes: Vec<Route>,

/// Visits the routes may take.
#[problem_fact_collection]
pub visits: Vec<Visit>,

/// The plan's score.
#[planning_score]
pub score: Option<HardSoftScore>,
}

fn constraints() -> impl ConstraintSet<Plan, HardSoftScore> {
(ConstraintFactory::<Plan, HardSoftScore>::new()
.for_each(Plan::routes())
.filter(|route: &Route| route.first_visit.is_none())
.penalize(HardSoftScore::of(1, 0))
.named("missing first visit"),)
}
17 changes: 17 additions & 0 deletions crates/solverforge/tests/generated_items_documented/route.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use solverforge::prelude::*;

/// A route with a list variable and a scalar variable.
#[planning_entity]
pub struct Route {
/// Stable route id.
#[planning_id]
pub id: usize,

/// Visits on this route, in order.
#[planning_list_variable(element_collection = "visits")]
pub visits: Vec<usize>,

/// The visit this route starts with.
#[planning_variable(value_range_provider = "visits", allows_unassigned = true)]
pub first_visit: Option<usize>,
}
9 changes: 9 additions & 0 deletions crates/solverforge/tests/generated_items_documented/visit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use solverforge::prelude::*;

/// A visit a route can take.
#[problem_fact]
pub struct Visit {
/// Stable visit id.
#[planning_id]
pub id: usize,
}
Loading