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
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,9 @@ All hot-path code must stay monomorphized.
- Avoid `.clone()` in move evaluation and scoring paths. Scoring streams do
not require `Clone` on entity types, so generic scoring code cannot clone an
entity; do not add a `Clone` bound to make one compile. Constraint analysis
describes an entity by its type name and `Debug` rendering (`EntityRef`) and
keeps no copy of it.
describes an entity by its type name, `Debug` rendering and source-rendered
planning id (`EntityRef`) and keeps no copy of it; planning ids are read
only on the cold explanation path.
- Preserve concrete types through the full solver pipeline.

Intentional type-erasure boundaries that should not be "fixed":
Expand Down
4 changes: 3 additions & 1 deletion crates/solverforge-macros/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ 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 __internal::AnalysisPlanningId for T` (always) — the `#[planning_id]` field rendered for constraint analysis (`Display`, else `Debug`, else `None`), or `None` without a `#[planning_id]` field; read only when a match is explained
- `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 `#[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()`
Expand Down Expand Up @@ -274,7 +275,7 @@ owner.
- `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. 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.
- 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], ModelPlanningIds>` wrapper for entity and fact collections (so their rows report their `#[planning_id]` in constraint analysis) or `SourceExtract<fn(&Plan) -> &[usize]>` for list-element collections, 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 @@ -284,6 +285,7 @@ owner.
**Generated code:**
- `impl ProblemFact for T` — `as_any()`
- `impl PlanningId for T` (if `#[planning_id]` present) — same as entity version
- `impl __internal::AnalysisPlanningId for T` (always) — same as entity version
- `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
25 changes: 25 additions & 0 deletions crates/solverforge-macros/src/planning_entity/expand/derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,29 @@ pub(crate) fn expand_derive(input: DeriveInput) -> Result<TokenStream, Error> {
TokenStream::new()
};

let analysis_planning_id_impl = if let Some(field) = id_field {
let field_name = field.ident.as_ref().unwrap();
quote! {
impl #impl_generics ::solverforge::__internal::AnalysisPlanningId for #name #ty_generics #where_clause {
fn analysis_planning_id(&self) -> ::core::option::Option<::std::string::String> {
#[allow(unused_imports)]
use ::solverforge::__internal::{
RenderPlanningIdDebug as _, RenderPlanningIdDisplay as _, RenderPlanningIdNone as _,
};
(&&&::solverforge::__internal::RenderPlanningId(&self.#field_name)).render_planning_id()
}
}
}
} else {
quote! {
impl #impl_generics ::solverforge::__internal::AnalysisPlanningId for #name #ty_generics #where_clause {
fn analysis_planning_id(&self) -> ::core::option::Option<::std::string::String> {
::core::option::Option::None
}
}
}
};

let id_field_descriptor = if let Some(field) = id_field {
let field_name = field.ident.as_ref().unwrap();
quote! { desc = desc.with_id_field(stringify!(#field_name)); }
Expand Down Expand Up @@ -413,6 +436,8 @@ pub(crate) fn expand_derive(input: DeriveInput) -> Result<TokenStream, Error> {

#planning_id_impl

#analysis_planning_id_impl

impl #impl_generics #name #ty_generics #where_clause {
#(#variable_helpers)*
#scalar_helpers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,11 @@ pub(super) fn generate_collection_source_methods(

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(
pub fn #field_name() -> ::solverforge::__internal::SourceExtract<
fn(&Self) -> &[#element_type],
::solverforge::__internal::ModelPlanningIds,
> {
::solverforge::__internal::model_source(
(|s: &Self| s.#field_name.as_slice()) as fn(&Self) -> &[#element_type],
::solverforge::__internal::ChangeSource::Descriptor(#descriptor_index_lit),
)
Expand All @@ -60,8 +63,11 @@ 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(
pub fn #field_name() -> ::solverforge::__internal::SourceExtract<
fn(&Self) -> &[#element_type],
::solverforge::__internal::ModelPlanningIds,
> {
::solverforge::__internal::model_source(
(|s: &Self| s.#field_name.as_slice()) as fn(&Self) -> &[#element_type],
#change_source,
)
Expand Down Expand Up @@ -139,10 +145,15 @@ pub(super) fn generate_constraint_stream_extensions(
field_name,
element_type,
change_source,
true,
);
}

for f in fact_fields.iter().chain(list_element_fields.iter()) {
let unowned = fact_fields
.iter()
.map(|f| (f, true))
.chain(list_element_fields.iter().map(|f| (f, false)));
for (f, planning_ids) in unowned {
let field_name = match f.ident.as_ref() {
Some(n) => n,
None => continue,
Expand All @@ -160,6 +171,7 @@ pub(super) fn generate_constraint_stream_extensions(
field_name,
element_type,
change_source,
planning_ids,
);
}

Expand All @@ -184,12 +196,32 @@ fn push_stream_extension_method(
field_name: &Ident,
element_type: &syn::Type,
change_source: TokenStream,
planning_ids: bool,
) {
// Entity and fact collections hold macro-annotated types, so their rows
// report their `#[planning_id]` in constraint analysis; list-element
// collections hold plain values and report none.
let (source_extract, source_fn) = if planning_ids {
(
quote! {
::solverforge::__internal::SourceExtract<
fn(&#solution_name) -> &[#element_type],
::solverforge::__internal::ModelPlanningIds,
>
},
quote! { ::solverforge::__internal::model_source },
)
} else {
(
quote! { ::solverforge::__internal::SourceExtract<fn(&#solution_name) -> &[#element_type]> },
quote! { ::solverforge::__internal::source },
)
};
let return_type = quote! {
::solverforge::__internal::UniConstraintStream<
#solution_name,
#element_type,
::solverforge::__internal::SourceExtract<fn(&#solution_name) -> &[#element_type]>,
#source_extract,
::solverforge::__internal::TrueFilter,
Sc,
>
Expand All @@ -204,7 +236,7 @@ fn push_stream_extension_method(
fn #field_name(self) -> #return_type {
::solverforge::stream::ConstraintFactory::for_each(
self,
::solverforge::__internal::source(
#source_fn(
(|s: &#solution_name| s.#field_name.as_slice())
as fn(&#solution_name) -> &[#element_type],
#change_source,
Expand Down
5 changes: 3 additions & 2 deletions crates/solverforge-macros/src/planning_solution_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ fn golden_solution_expansion_emits_model_sources_and_descriptor() {

assert!(expanded.contains("impl :: solverforge :: __internal :: PlanningSolution for Plan"));
assert!(expanded.contains(
"pub fn workers () -> :: solverforge :: __internal :: SourceExtract < fn (& Self) -> & [Worker] >"
"pub fn workers () -> :: solverforge :: __internal :: SourceExtract < fn (& Self) -> & [Worker] , :: solverforge :: __internal :: ModelPlanningIds , >"
));
assert!(expanded.contains(
"pub fn tasks () -> :: solverforge :: __internal :: SourceExtract < fn (& Self) -> & [Task] >"
"pub fn tasks () -> :: solverforge :: __internal :: SourceExtract < fn (& Self) -> & [Task] , :: solverforge :: __internal :: ModelPlanningIds , >"
));
assert!(expanded.contains(":: solverforge :: __internal :: model_source ("));
assert!(expanded.contains("ChangeSource :: Static"));
assert!(expanded.contains("ChangeSource :: Descriptor (0)"));
assert!(expanded
Expand Down
25 changes: 25 additions & 0 deletions crates/solverforge-macros/src/problem_fact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,29 @@ pub fn expand_derive(input: DeriveInput) -> Result<TokenStream, Error> {
TokenStream::new()
};

let analysis_planning_id_impl = if let Some(field) = id_field {
let field_name = field.ident.as_ref().unwrap();
quote! {
impl #impl_generics ::solverforge::__internal::AnalysisPlanningId for #name #ty_generics #where_clause {
fn analysis_planning_id(&self) -> ::core::option::Option<::std::string::String> {
#[allow(unused_imports)]
use ::solverforge::__internal::{
RenderPlanningIdDebug as _, RenderPlanningIdDisplay as _, RenderPlanningIdNone as _,
};
(&&&::solverforge::__internal::RenderPlanningId(&self.#field_name)).render_planning_id()
}
}
}
} else {
quote! {
impl #impl_generics ::solverforge::__internal::AnalysisPlanningId for #name #ty_generics #where_clause {
fn analysis_planning_id(&self) -> ::core::option::Option<::std::string::String> {
::core::option::Option::None
}
}
}
};

let id_field_descriptor = if let Some(field) = id_field {
let field_name = field.ident.as_ref().unwrap();
quote! { desc = desc.with_id_field(stringify!(#field_name)); }
Expand All @@ -67,6 +90,8 @@ pub fn expand_derive(input: DeriveInput) -> Result<TokenStream, Error> {

#planning_id_impl

#analysis_planning_id_impl

impl #impl_generics #name #ty_generics #where_clause {
#[doc(hidden)]
pub fn problem_fact_descriptor(
Expand Down
Loading
Loading