1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! Per-function analysis: inherent and trait impl bodies, signatures for codegen.
use std::collections::{HashMap, HashSet};
use crate::auto_clone::AutoCloneAnalysis;
use crate::parser::*;
use super::{
AnalyzedFunction, Analyzer, FunctionSignature, ImplSelfFieldContext, OwnershipMode,
SignatureRegistry,
};
impl<'ast> Analyzer<'ast> {
/// All methods for `type_name` across every `impl` block in the program (including inherent + trait impls).
/// Used so `self.helper()` in `impl Trait for T` resolves `helper` from `impl T` on the same type.
pub(crate) fn merged_impl_methods_for_type(
program: &Program<'ast>,
type_name: &str,
) -> HashMap<String, FunctionDecl<'ast>> {
let type_base = type_name.split('<').next().unwrap_or(type_name);
let mut merged = HashMap::new();
Self::collect_impl_methods_recursive(&program.items, type_base, &mut merged);
merged
}
pub(crate) fn collect_impl_methods_recursive(
items: &[Item<'ast>],
type_base: &str,
merged: &mut HashMap<String, FunctionDecl<'ast>>,
) {
for item in items {
match item {
Item::Impl { block, .. } => {
let block_base = block
.type_name
.split('<')
.next()
.unwrap_or(&block.type_name);
if block_base == type_base {
for f in &block.functions {
merged.insert(f.name.clone(), f.clone());
}
}
}
Item::Mod { items: inner, .. } => {
Self::collect_impl_methods_recursive(inner, type_base, merged);
}
_ => {}
}
}
}
/// Analyze a function within an impl block (has access to other methods for cross-method analysis)
pub(crate) fn analyze_function_in_impl(
&mut self,
func: &FunctionDecl<'ast>,
impl_block: &crate::parser::ast::ImplBlock<'ast>,
program: &Program<'ast>,
registry: &SignatureRegistry,
) -> Result<AnalyzedFunction<'ast>, String> {
// Same-type impl merge: trait impl methods can call inherent helpers on the same type.
self.current_impl_functions = Some(Self::merged_impl_methods_for_type(
program,
&impl_block.type_name,
));
let impl_base = impl_block
.type_name
.split('<')
.next()
.unwrap_or(impl_block.type_name.as_str())
.to_string();
self.self_impl_context = Some(ImplSelfFieldContext::new(impl_base, program));
let mut analyzed = self.analyze_function(func, registry)?;
// Inherent impls: `for x in self.field` + `x.foo()` where `foo` is `&mut self` on a trait object
// requires `&mut self` on the outer method (codegen emits `&mut self.field`).
if impl_block.trait_name.is_none() {
self.maybe_upgrade_self_for_dispatch_for_loops(
&mut analyzed,
func,
impl_block.type_name.as_str(),
program,
registry,
);
}
// Clear impl block after analysis
self.self_impl_context = None;
self.current_impl_functions = None;
Ok(analyzed)
}
/// Infer `self` receiver ownership for impl methods. Windjammer always writes bare
/// `self` in source; codegen maps to `&self`, `&mut self`, or owned `self`.
fn infer_impl_self_receiver_ownership(
&self,
func: &FunctionDecl<'ast>,
registry: &SignatureRegistry,
) -> OwnershipMode {
if func.is_extern && func.body.is_empty() && func.parent_type.is_some() {
return OwnershipMode::MutBorrowed;
}
let modifies_fields =
self.function_modifies_self_fields_with_registry(func, Some(registry));
let returns_self = self.function_returns_self(func);
let body_moves_fields = self.function_body_moves_non_copy_self_fields(func);
let snapshot_factory = self.function_returns_new_instance_from_self_fields(func);
let consumes_self = (!snapshot_factory && body_moves_fields)
|| self.function_moves_self_into_return(func)
|| (!snapshot_factory
&& (returns_self
|| self.function_body_consumes_bare_self(func)
|| self.function_calls_consuming_method_on_self(func, registry)
|| self.function_matches_on_self(func)
|| self.function_consumes_self_field_elements(func, Some(registry))));
if consumes_self {
OwnershipMode::Owned
} else if modifies_fields {
OwnershipMode::MutBorrowed
} else if self.is_used_in_binary_op("self", &func.body) {
OwnershipMode::Owned
} else {
OwnershipMode::Borrowed
}
}
pub(crate) fn analyze_function(
&mut self,
func: &FunctionDecl<'ast>,
registry: &SignatureRegistry,
) -> Result<AnalyzedFunction<'ast>, String> {
let mut inferred_ownership = HashMap::new();
// Check if this is a game decorator function
let is_game_decorator = func.decorators.iter().any(|d| {
matches!(
d.name.as_str(),
"init" | "update" | "render" | "render3d" | "input" | "cleanup"
)
});
let is_render3d = func.decorators.iter().any(|d| d.name == "render3d");
// THE WINDJAMMER WAY: Auto-Self Inference
// If a method uses `self` in its body but doesn't declare it as a parameter,
// automatically infer and add it.
let declares_self = func.parameters.iter().any(|p| p.name == "self");
let uses_self = self.function_uses_identifier("self", &func.body);
if uses_self && !declares_self {
// Auto-infer self ownership based on usage
let modifies_fields =
self.function_modifies_self_fields_with_registry(func, Some(registry));
let returns_self = self.function_returns_self(func);
let body_moves_fields = self.function_body_moves_non_copy_self_fields(func);
let snapshot_factory = self.function_returns_new_instance_from_self_fields(func);
let consumes_self = (!snapshot_factory && body_moves_fields)
|| self.function_moves_self_into_return(func)
|| (!snapshot_factory
&& (returns_self
|| self.function_body_consumes_bare_self(func)
|| self.function_calls_consuming_method_on_self(func, registry)
|| self.function_matches_on_self(func)
|| self.function_consumes_self_field_elements(func, Some(registry))));
let self_ownership = if consumes_self {
OwnershipMode::Owned
} else if modifies_fields {
OwnershipMode::MutBorrowed
} else if self.is_used_in_binary_op("self", &func.body) {
OwnershipMode::Owned
} else {
OwnershipMode::Borrowed
};
// Store inferred self ownership
inferred_ownership.insert("self".to_string(), self_ownership);
}
// Analyze each parameter to infer ownership mode
for (i, param) in func.parameters.iter().enumerate() {
let mode = match param.ownership {
OwnershipHint::Owned => {
// Windjammer writes `self` without & — in impl methods, infer receiver
// ownership from body usage (distance(self) → &self, not owned self).
if param.name == "self" && func.parent_type.is_some() {
self.infer_impl_self_receiver_ownership(func, registry)
} else {
OwnershipMode::Owned
}
}
OwnershipHint::Mut => {
if Self::is_generic_type_param(¶m.type_) {
OwnershipMode::Owned
} else {
OwnershipMode::MutBorrowed
}
}
OwnershipHint::Ref => {
// SMART FIX: If user wrote &self but function modifies fields, upgrade to &mut self
// This prevents a common user error
if param.name == "self"
&& self.function_modifies_self_fields_with_registry(func, Some(registry))
{
OwnershipMode::MutBorrowed
} else {
OwnershipMode::Borrowed
}
}
OwnershipHint::Inferred => {
// Special case: Game decorator functions always take &mut for first parameter (game state)
if is_game_decorator && i == 0 {
OwnershipMode::MutBorrowed
} else if is_render3d && i == 2 {
// Special case: @render3d functions take &mut for camera parameter (3rd param)
OwnershipMode::MutBorrowed
} else if param.name == "self" {
// `extern impl Type { fn f(self) {} }` / empty extern bodies: the signature is an
// FFI stub; bare `self` in Windjammer means a receiver is passed — for inherent
// impl methods, treat as `&mut self` so `self.field.method()` is dispatchable
// without moving the struct (see ownership_self_field_mutation test).
if func.is_extern && func.body.is_empty() && func.parent_type.is_some() {
OwnershipMode::MutBorrowed
} else {
let modifies_fields = self
.function_modifies_self_fields_with_registry(func, Some(registry));
let returns_self = self.function_returns_self(func);
let body_moves_fields =
self.function_body_moves_non_copy_self_fields(func);
let snapshot_factory =
self.function_returns_new_instance_from_self_fields(func);
let consumes_self = (!snapshot_factory && body_moves_fields)
|| self.function_moves_self_into_return(func)
|| (!snapshot_factory
&& (returns_self
|| self.function_body_consumes_bare_self(func)
|| self.function_calls_consuming_method_on_self(
func, registry,
)
|| self.function_matches_on_self(func)
|| self.function_consumes_self_field_elements(
func,
Some(registry),
)));
if consumes_self {
OwnershipMode::Owned
} else if modifies_fields {
OwnershipMode::MutBorrowed
} else if self.is_used_in_binary_op("self", &func.body) {
OwnershipMode::Owned
} else {
OwnershipMode::Borrowed
}
}
} else {
// For Copy types, check if they're mutated first
// Mutated Copy types should be &mut, not Owned
let is_copy = self.is_copy_type(¶m.type_);
if param.is_mutable {
if Self::is_generic_type_param(¶m.type_) {
OwnershipMode::Owned
} else {
let passthrough = self.infer_passthrough_ownership(
¶m.name,
¶m.type_,
&func.body,
registry,
&func.name,
func,
);
if passthrough == Some(OwnershipMode::MutBorrowed) {
OwnershipMode::Owned
} else {
OwnershipMode::MutBorrowed
}
}
} else if is_copy {
let mutated = self.is_mutated(
¶m.name,
&func.body,
registry,
Some(¶m.type_),
);
let passthrough_mut = matches!(
self.infer_passthrough_ownership(
¶m.name,
¶m.type_,
&func.body,
registry,
&func.name,
func,
),
Some(OwnershipMode::MutBorrowed)
);
if std::env::var("WJ_DEBUG_OWNERSHIP").is_ok() {
eprintln!(
" [OWNERSHIP-COPY] {} in {}: is_copy=true mutated={} passthrough_mut={} (type: {:?})",
param.name, func.name, mutated, passthrough_mut, param.type_
);
}
if mutated || passthrough_mut {
OwnershipMode::MutBorrowed
} else {
OwnershipMode::Owned
}
} else {
// Perform inference based on usage in function body
let inferred_mode = self.infer_parameter_ownership(
¶m.name,
¶m.type_,
&func.body,
&func.return_type,
registry,
&func.name,
func,
)?;
// DEBUG: Log ownership inference for non-Copy parameters
if std::env::var("WJ_DEBUG_OWNERSHIP").is_ok() {
eprintln!(
" [OWNERSHIP] {} in {}: {:?} (type: {:?})",
param.name, func.name, inferred_mode, param.type_
);
}
inferred_mode
}
}
}
};
inferred_ownership.insert(param.name.clone(), mode);
}
// During multipass convergence, skip expensive optimization detectors.
// Only ownership inference matters for convergence; codegen-only
// optimizations run in the final pass.
let (
clone_optimizations,
struct_mapping_optimizations,
string_optimizations,
assignment_optimizations,
defer_drop_optimizations,
auto_clone_analysis,
mutated_variables,
mutated_parameters,
const_static_optimizations,
smallvec_optimizations,
cow_optimizations,
cache_locality,
str_ref_optimizable_params,
inferred_param_types,
) = if self.convergence_only {
// str_ref analysis is cheap and affects signatures (param_types change
// from String to &str), so it MUST run during convergence.
// Only skip the truly expensive codegen-only optimizations.
let str_ref_optimizable_params =
self.analyze_str_ref_optimizable_params(func, registry);
let inferred_param_types: Vec<Type> = func
.parameters
.iter()
.map(|param| {
if str_ref_optimizable_params.contains(¶m.name) {
Type::Reference(Box::new(Type::Custom("str".to_string())))
} else {
param.type_.clone()
}
})
.collect();
(
Vec::new(),
Vec::new(),
Vec::new(),
Vec::new(),
Vec::new(),
AutoCloneAnalysis::default(),
HashSet::new(),
HashSet::new(),
Vec::new(),
Vec::new(),
Vec::new(),
super::CacheLocalityAnalysis::default(),
str_ref_optimizable_params,
inferred_param_types,
)
} else {
let clone_optimizations = self.detect_unnecessary_clones(func);
let struct_mapping_optimizations = self.detect_struct_mappings(func);
let string_optimizations = self.detect_string_optimizations(func);
let assignment_optimizations = self.detect_assignment_optimizations(func);
let defer_drop_optimizations = self.detect_defer_drop_opportunities(func, registry);
let auto_clone_analysis = AutoCloneAnalysis::analyze_function(func);
self.track_mutations(&func.body, registry);
let mutated_variables = self.mutated_variables.clone();
let mut mutated_parameters = HashSet::new();
for param in &func.parameters {
if self.is_mutated(¶m.name, &func.body, registry, Some(¶m.type_)) {
mutated_parameters.insert(param.name.clone());
}
}
let const_static_optimizations = Vec::new();
let smallvec_optimizations = Vec::new();
let cow_optimizations = Vec::new();
let cache_locality = super::CacheLocalityAnalysis::default();
let str_ref_optimizable_params =
self.analyze_str_ref_optimizable_params(func, registry);
let inferred_param_types: Vec<Type> = func
.parameters
.iter()
.map(|param| {
if str_ref_optimizable_params.contains(¶m.name) {
Type::Reference(Box::new(Type::Custom("str".to_string())))
} else {
param.type_.clone()
}
})
.collect();
(
clone_optimizations,
struct_mapping_optimizations,
string_optimizations,
assignment_optimizations,
defer_drop_optimizations,
auto_clone_analysis,
mutated_variables,
mutated_parameters,
const_static_optimizations,
smallvec_optimizations,
cow_optimizations,
cache_locality,
str_ref_optimizable_params,
inferred_param_types,
)
};
Ok(AnalyzedFunction {
decl: func.clone(),
inferred_ownership,
inferred_param_types,
mutated_variables,
mutated_parameters,
auto_clone_analysis,
clone_optimizations,
struct_mapping_optimizations,
string_optimizations,
assignment_optimizations,
defer_drop_optimizations,
const_static_optimizations,
smallvec_optimizations,
cow_optimizations,
cache_locality,
str_ref_optimizable_params,
})
}
/// Analyze a function that implements a trait method
/// Use the trait's method signature instead of inferring
pub(crate) fn analyze_trait_impl_function(
&mut self,
func: &FunctionDecl<'ast>,
trait_name: &str,
impl_block: &crate::parser::ast::ImplBlock<'ast>,
program: &Program<'ast>,
registry: &SignatureRegistry,
) -> Result<AnalyzedFunction<'ast>, String> {
// Trait impl bodies may call `self.inherent_helper()` from `impl Type` — merge those decls.
self.current_impl_functions = Some(Self::merged_impl_methods_for_type(
program,
&impl_block.type_name,
));
let impl_base = impl_block
.type_name
.split('<')
.next()
.unwrap_or(impl_block.type_name.as_str())
.to_string();
self.self_impl_context = Some(ImplSelfFieldContext::new(impl_base, program));
let analyzed_base = self.analyze_function(func, registry);
self.self_impl_context = None;
self.current_impl_functions = None;
let mut analyzed = analyzed_base?;
// Look up the trait definition
// Try both the full trait name and just the last segment (e.g., "std::ops::Add" -> "Add")
let trait_key = if let Some(pos) = trait_name.rfind("::") {
&trait_name[pos + 2..]
} else {
trait_name
};
let is_std_operator_trait =
crate::type_classification::is_consuming_operator_trait(trait_key);
// For standard operator traits, use `self` (owned) instead of `&self`
if is_std_operator_trait {
// Standard operator trait (Add, Sub, Mul, etc.) - not defined in Windjammer stdlib
// These traits use `self` (owned) for the first parameter (self), not `&self`
// Example: `fn add(self, rhs: Rhs) -> Output`
// For the first parameter (self), use Owned for Copy types
if let Some(first_param) = func.parameters.first() {
if first_param.name == "self" {
// Use Owned (self) for operator traits on Copy types
analyzed
.inferred_ownership
.insert("self".to_string(), OwnershipMode::Owned);
}
}
} else if let Some(trait_decl) = self.trait_definitions.get(trait_key) {
// Defer mutable trait registry updates until after this immutable borrow ends.
let mut self_receiver_upgrades: Vec<(String, String, String, OwnershipMode)> =
Vec::new();
// Find the matching trait method
if let Some(trait_method) = trait_decl.methods.iter().find(|m| m.name == func.name) {
// Override ALL parameters to match trait signature
// Trait implementations must match the trait's exact signature
// Match by POSITION, not by name (trait uses "rhs", impl might use "other")
for (i, trait_param) in trait_method.parameters.iter().enumerate() {
// Get the corresponding parameter from the implementation by position
if let Some(impl_param) = func.parameters.get(i) {
// WINDJAMMER PHILOSOPHY: Use ANALYZED trait method ownership, not AST ownership!
// The AST might have `self` (Owned) but analysis infers `&self` (Borrowed).
// Check if this trait method was analyzed (has default implementation)
let trait_methods_opt = self
.analyzed_trait_methods
.get(trait_key)
.or_else(|| self.analyzed_trait_methods.get(trait_name));
let trait_mode = if let Some(trait_methods) = trait_methods_opt {
if let Some(analyzed_trait_method) = trait_methods.get(&func.name) {
analyzed_trait_method
.inferred_ownership
.get(&trait_param.name)
.copied()
} else {
None
}
} else {
None
};
let impl_body_mode =
analyzed.inferred_ownership.get(&impl_param.name).copied();
let final_mode = if impl_param.name == "self" {
match (trait_mode, impl_body_mode) {
(Some(trait_m), Some(impl_m)) => {
Self::merge_borrow_trait_receivers(trait_m, impl_m)
}
(Some(trait_m), None) => trait_m,
(None, Some(impl_m)) => impl_m,
(None, None) => self.convert_ownership_hint_to_mode(
&trait_param.ownership,
&trait_param.name,
),
}
} else if let Some(mode) = trait_mode {
mode
} else {
impl_body_mode.unwrap_or_else(|| {
self.convert_ownership_hint_to_mode(
&trait_param.ownership,
&trait_param.name,
)
})
};
if impl_param.name == "self" {
if let Some(trait_m) = trait_mode {
if final_mode != trait_m {
self_receiver_upgrades.push((
trait_name.to_string(),
trait_key.to_string(),
func.name.clone(),
final_mode,
));
}
}
}
// INSERT or UPDATE with the final ownership mode
analyzed
.inferred_ownership
.insert(impl_param.name.clone(), final_mode);
}
}
}
for (upgrade_trait_name, upgrade_trait_key, method_name, receiver) in
self_receiver_upgrades
{
self.upgrade_trait_method_self_receiver(
&upgrade_trait_name,
&upgrade_trait_key,
&method_name,
receiver,
);
}
}
// E0053: Parameter types in generated Rust must match the trait declaration (impls may
// rename parameters or use incompatible aliases). Ownership already matches the trait above.
if !is_std_operator_trait {
if let Some(analyzed_trait_fn) = self
.analyzed_trait_methods
.get(trait_key)
.and_then(|m| m.get(&func.name))
.or_else(|| {
self.analyzed_trait_methods
.get(trait_name)
.and_then(|m| m.get(&func.name))
})
{
for (i, _) in func.parameters.iter().enumerate() {
if let Some(trait_ty) = analyzed_trait_fn.inferred_param_types.get(i) {
if i < analyzed.inferred_param_types.len() {
analyzed.inferred_param_types[i] = trait_ty.clone();
}
}
}
}
// If multipass never stored analyzed trait fn types, still copy AST parameter types so
// generated Rust matches the trait item (E0053).
if let Some(trait_decl) = self.trait_definitions.get(trait_key) {
if let Some(trait_method) = trait_decl.methods.iter().find(|m| m.name == func.name)
{
let tf = self
.analyzed_trait_methods
.get(trait_key)
.and_then(|m| m.get(&func.name))
.or_else(|| {
self.analyzed_trait_methods
.get(trait_name)
.and_then(|m| m.get(&func.name))
});
for (i, trait_param) in trait_method.parameters.iter().enumerate() {
if i >= analyzed.inferred_param_types.len() {
break;
}
let use_ast = tf.and_then(|t| t.inferred_param_types.get(i)).is_none();
if use_ast {
analyzed.inferred_param_types[i] = trait_param.type_.clone();
}
}
}
}
}
Ok(analyzed)
}
pub(crate) fn build_signature(&self, func: &AnalyzedFunction) -> FunctionSignature {
let param_ownership: Vec<OwnershipMode> = func
.decl
.parameters
.iter()
.map(|param| {
// CRITICAL FIX: Check the actual type annotation FIRST
// If parameter is explicitly declared as &T or &mut T, respect that
use crate::parser::Type;
match ¶m.type_ {
Type::Reference(_) => {
// Parameter is explicitly &T - must borrow
return OwnershipMode::Borrowed;
}
Type::MutableReference(_) => {
// Parameter is explicitly &mut T - must mut borrow
return OwnershipMode::MutBorrowed;
}
_ => {
// Not an explicit reference, use inference
}
}
if Self::is_windjammer_text_param_type(¶m.type_)
&& self.is_only_hashmap_lookup_key_param(
¶m.name,
&func.decl.body,
&func.decl,
)
{
return OwnershipMode::Borrowed;
}
let inferred = func
.inferred_ownership
.get(¶m.name)
.cloned()
.unwrap_or(OwnershipMode::Owned);
// CRITICAL: Generic type parameters (like G in fn foo<G: Trait>(g: G))
// should ALWAYS be Owned. The trait bound is on G, not on &G.
// Adding & at call sites would break trait bounds.
if Self::is_generic_type_param(¶m.type_) {
return OwnershipMode::Owned;
}
// Copy types are always passed by value (Owned) unless mutated
// This must match the logic in codegen.rs
if self.is_copy_type(¶m.type_) {
// Copy types: pass by value unless they need to be mutated
if inferred == OwnershipMode::MutBorrowed {
OwnershipMode::MutBorrowed
} else {
OwnershipMode::Owned
}
} else {
// THE WINDJAMMER WAY: The compiler infers ownership, not the user.
// Non-Copy types follow the analyzer's inference:
// - Borrowed: parameter is only read (default for read-only params)
// - MutBorrowed: parameter is mutated
// - Owned: parameter is consumed (returned, stored, iterated, etc.)
//
// Users write `data: Vec<f32>` and the compiler figures out whether
// it should be `&Vec<f32>`, `&mut Vec<f32>`, or `Vec<f32>` in Rust.
// This matches call sites where `&self.data` is naturally passed.
inferred
}
})
.collect();
// PHASE 2 STRING OPTIMIZATION: Use inferred parameter types when available
// The analyzer determines which string parameters can be &str vs &String
// based on how they're used in the function body.
let mut param_types: Vec<Type> = func
.decl
.parameters
.iter()
.enumerate()
.map(|(idx, param)| {
// Use inferred type if available (Phase 2 optimization)
// Otherwise fall back to explicit type annotation
func.inferred_param_types
.get(idx)
.cloned()
.unwrap_or_else(|| param.type_.clone())
})
.collect();
let explicit_self = func
.decl
.parameters
.first()
.is_some_and(|p| p.name == "self" || p.name == "mut self");
// Omitted `self` in source (`fn touch() { self... }`): analyzer stores ownership under
// "self" but decl.parameters has no receiver. SignatureRegistry must still expose
// `has_self_receiver` + `param_ownership[0]` so cross-type calls (e.g. `.touch()`) resolve.
let synthetic_self_receiver =
func.inferred_ownership.contains_key("self") && !explicit_self;
let mut param_ownership = param_ownership;
if synthetic_self_receiver {
let self_mode = func
.inferred_ownership
.get("self")
.copied()
.unwrap_or(OwnershipMode::Borrowed);
param_ownership.insert(0, self_mode);
let self_ty = func
.decl
.parent_type
.as_ref()
.map(|n| Type::Custom(n.clone()))
.unwrap_or(Type::Custom("Self".to_string()));
param_types.insert(0, self_ty);
}
let has_self_receiver = explicit_self || synthetic_self_receiver;
// Phase 2: `string` may become `Reference(Custom("str"))` in inferred_param_types while
// ownership inference still marks the parameter `Owned` (e.g. forwarding calls where
// the body is only `Call(FieldAccess)` and string-ref analysis does not recurse).
// Rust lowers these parameters as `&str` with a borrow — call-site helpers that key
// off `param_ownership` (`should_add_to_string`, `OwnershipMode::Owned` in bare `Call`)
// must agree or we emit `arg.to_string()` / bad conversions for `&str` → `&str` calls.
use crate::parser::Type as PType;
for (idx, ty) in param_types.iter().enumerate() {
if matches!(
ty,
PType::Reference(inner)
if matches!(&**inner, PType::Custom(s) if s == "str")
) {
if let Some(slot) = param_ownership.get_mut(idx) {
*slot = OwnershipMode::Borrowed;
}
}
}
// Extract return type for smart string inference
let return_type = func.decl.return_type.clone();
FunctionSignature {
name: func.decl.name.clone(),
param_types,
param_ownership,
return_type,
return_ownership: OwnershipMode::Owned, // For now, always owned
has_self_receiver,
is_extern: func.decl.is_extern,
}
}
/// Register all analyzed trait methods into a signature registry under
/// `TraitName::method_name` keys.
pub fn register_trait_methods_in_registry(
&self,
trait_methods: &std::collections::HashMap<
String,
std::collections::HashMap<String, AnalyzedFunction<'_>>,
>,
registry: &mut super::SignatureRegistry,
) {
for (trait_name, methods) in trait_methods {
for (method_name, analyzed_func) in methods {
let sig = self.build_signature(analyzed_func);
let qualified_name = format!("{}::{}", trait_name, method_name);
registry.add_function(qualified_name, sig);
}
}
}
}