@@ -35,24 +35,85 @@ export async function* generateRegions(
3535 variables
3636 } = options ;
3737
38+ // Stack of rename mappings for template references with yields
39+ const renameStack : Array < Record < string , string > > = [ ] ;
40+
41+ // Stack of template definitions for inline templates
42+ const templatesStack : Array < Pointer . Templates > = [ ] ;
43+
3844 const stack : Memo [ ] = [ Memo . dereferencePointer ( pointer ) ] ;
3945 while ( stack . length > 0 ) {
4046 const memo : Memo = stack . pop ( ) as Memo ;
4147
4248 let memos : Memo [ ] = [ ] ;
4349 switch ( memo . kind ) {
4450 case "dereference-pointer" : {
45- memos = yield * processPointer ( memo . pointer , options ) ;
51+ // Merge inline templates with base templates (inline takes precedence)
52+ const currentTemplates = templatesStack . reduce (
53+ ( acc , templates ) => ( { ...acc , ...templates } ) ,
54+ options . templates
55+ ) ;
56+
57+ // Process the pointer, intercepting yielded regions to apply renames
58+ const process = processPointer ( memo . pointer , {
59+ ...options ,
60+ templates : currentTemplates
61+ } ) ;
62+ let result = await process . next ( ) ;
63+ while ( ! result . done ) {
64+ let region = result . value ;
65+
66+ // Apply rename if in context and region has a name in mapping
67+ const currentMapping = renameStack [ renameStack . length - 1 ] ;
68+ if ( currentMapping && region . name ) {
69+ const newName = currentMapping [ region . name ] ;
70+ if ( newName && newName !== region . name ) {
71+ region = { ...region , name : newName } ;
72+ }
73+ }
74+
75+ yield region ;
76+ result = await process . next ( ) ;
77+ }
78+ memos = result . value ;
4679 break ;
4780 }
4881 case "save-regions" : {
49- Object . assign ( regions , memo . regions ) ;
82+ for ( const [ name , region ] of Object . entries ( memo . regions ) ) {
83+ // Save under original name for internal reference resolution
84+ regions [ name ] = region ;
85+ }
5086 break ;
5187 }
5288 case "save-variables" : {
5389 Object . assign ( variables , memo . variables ) ;
5490 break ;
5591 }
92+ case "push-region-renames" : {
93+ renameStack . push ( memo . mapping ) ;
94+ break ;
95+ }
96+ case "pop-region-renames" : {
97+ // Apply renames when exiting the context: add mappings from
98+ // original names to new names for external reference resolution
99+ const mapping = renameStack . pop ( ) ;
100+ if ( mapping ) {
101+ for ( const [ originalName , newName ] of Object . entries ( mapping ) ) {
102+ if ( originalName in regions && newName !== originalName ) {
103+ regions [ newName ] = { ...regions [ originalName ] , name : newName } ;
104+ }
105+ }
106+ }
107+ break ;
108+ }
109+ case "push-templates" : {
110+ templatesStack . push ( memo . templates ) ;
111+ break ;
112+ }
113+ case "pop-templates" : {
114+ templatesStack . pop ( ) ;
115+ break ;
116+ }
56117 }
57118
58119 // add new memos to the stack in reverse order
0 commit comments