@papercraftgames/estragon 0.1.0-beta.11 → 0.1.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -226,7 +226,7 @@ func _child_result(tokens: Array, span) -> void:
226
226
  if begin<tokens.size()-1: _child_result(tokens.slice(begin,tokens.size()-1),span)
227
227
  return
228
228
  # Unknown native expressions (locals, typed helper returns, Array.map) are
229
- # runtime-validated as a complete desired tree. Obvious scalar/live Node
229
+ # runtime-validated as a complete desired tree. Obvious scalar/newly-created Node
230
230
  # leaves fail at their authored span, including conditional alternatives.
231
231
  if not tokens.is_empty():
232
232
  var first: String = tokens[0].text
@@ -234,7 +234,7 @@ func _child_result(tokens: Array, span) -> void:
234
234
  var scalar_call: bool = tokens.size()>1 and tokens[1].text=="(" and _direct_call(tokens,1) and first in ["int","float","bool","String","StringName","Vector2","Vector3","Color","Dictionary","NodePath"]
235
235
  if tokens[0].kind=="identifier" and first not in ["true","false"] and not scalar_call and (not constructor or resolver.aliases.get(first,"")==(Element as Script).resource_path):
236
236
  return
237
- _error("GGX children require Element, null or nested Arrays of descriptions; scalars/live Nodes reject",tokens[0].span if not tokens.is_empty() else span)
237
+ _error("GGX children require Element, null, nested Arrays or borrowed scene children; scalars/newly constructed Nodes reject",tokens[0].span if not tokens.is_empty() else span)
238
238
 
239
239
  func _native_type(property: Dictionary) -> String:
240
240
  if property.type == TYPE_OBJECT:
@@ -22,6 +22,8 @@ var _path := ""
22
22
  var _symbols: Dictionary = {}
23
23
  var _aliases: Dictionary = {}
24
24
  var _owners: Dictionary = {}
25
+ var _scoped: Dictionary = {}
26
+ var _blocks: Dictionary = {}
25
27
  var _base := "Node"
26
28
  var _native_cache: Dictionary = {}
27
29
  var _types = Validator.new(Source.new(""))
@@ -57,17 +59,35 @@ func _resolve_path(raw: String, source: String) -> String:
57
59
  if value.is_absolute_path(): return value.simplify_path()
58
60
  var output := Build.output_for(source) if source.ends_with(".gogo") else source
59
61
  return output.get_base_dir().path_join(value).simplify_path()
62
+ func _declared_type(tokens: Array, start: int) -> String:
63
+ if start>=tokens.size() or not tokens[start].text.is_valid_identifier(): return ""
64
+ var type: String = tokens[start].text
65
+ for index in range(start+1,mini(start+17,tokens.size()-1),2):
66
+ if tokens[index].text!="." or not tokens[index+1].text.is_valid_identifier(): break
67
+ type += "."+tokens[index+1].text
68
+ return type
60
69
  func _declarations(text: String, source: String) -> Dictionary:
61
70
  var tokens := _tokens(text)
71
+ # Indentation block identities distinguish a local declaration from names
72
+ # in an exited/sibling block. Compute once with the declaration index.
73
+ var blocks := {}
74
+ var stack: Array = []
75
+ for token in tokens:
76
+ if blocks.has(token.row): continue
77
+ while not stack.is_empty() and stack[-1].indent>token.indent: stack.pop_back()
78
+ if token.indent>0 and (stack.is_empty() or stack[-1].indent<token.indent): stack.append({"indent":token.indent,"id":token.row})
79
+ if token.indent==0: stack.clear()
80
+ blocks[token.row] = stack.map(func(block): return block.id)
62
81
  var symbols: Dictionary = {}
63
82
  var aliases: Dictionary = {}
64
83
  var base := ""
65
84
  var owner := ""
66
85
  var owners: Dictionary = {}
86
+ var scoped: Dictionary = {}
67
87
  var required_initializer := false
68
88
  for index in range(tokens.size()):
69
89
  var word: String = tokens[index].text
70
- if tokens[index].indent == 0: owners[tokens[index].row] = ""
90
+ if tokens[index].indent == 0 and not owners.has(tokens[index].row): owners[tokens[index].row] = ""
71
91
  elif not owners.has(tokens[index].row): owners[tokens[index].row] = owner
72
92
  if word == "extends" and tokens[index].indent == 0 and index+1 < tokens.size():
73
93
  base = _resolve_path(tokens[index+1].text,source) if tokens[index+1].kind == "string" else tokens[index+1].text
@@ -80,9 +100,18 @@ func _declarations(text: String, source: String) -> Dictionary:
80
100
  owners[tokens[index].row] = owner
81
101
  if name == "_init" and index+3 < tokens.size() and tokens[index+3].text != ")": required_initializer = true
82
102
  var type := ""
83
- if index+3 < tokens.size() and tokens[index+2].text == ":": type = tokens[index+3].text
84
- symbols[name] = {"type":type,"owner":scope,"writable":true,"kind":CodeEdit.KIND_FUNCTION if word == "func" else (CodeEdit.KIND_SIGNAL if word == "signal" else (CodeEdit.KIND_CONSTANT if word == "const" else (CodeEdit.KIND_CLASS if word in ["class","class_name"] else (CodeEdit.KIND_VARIABLE if not scope.is_empty() else CodeEdit.KIND_MEMBER))))}
85
- if word == "func": symbols[name].hint = text.split("\n")[tokens[index].row].strip_edges().trim_prefix("func ").trim_suffix(":")
103
+ if index+3 < tokens.size() and tokens[index+2].text == ":": type = _declared_type(tokens,index+3)
104
+ symbols[name] = {"type":type,"owner":scope,"row":tokens[index].row,"block":blocks.get(tokens[index].row,[]),"writable":true,"kind":CodeEdit.KIND_FUNCTION if word == "func" else (CodeEdit.KIND_SIGNAL if word == "signal" else (CodeEdit.KIND_CONSTANT if word == "const" else (CodeEdit.KIND_CLASS if word in ["class","class_name"] else (CodeEdit.KIND_VARIABLE if not scope.is_empty() else CodeEdit.KIND_MEMBER))))}
105
+ if word == "func":
106
+ symbols[name].hint = text.split("\n")[tokens[index].row].strip_edges().trim_prefix("func ").trim_suffix(":")
107
+ var depth := 0
108
+ for cursor in range(index+2,mini(index+258,tokens.size()-2)):
109
+ if tokens[cursor].text == "(": depth += 1
110
+ elif tokens[cursor].text == ")":
111
+ depth -= 1
112
+ if depth == 0:
113
+ if tokens[cursor+1].text == "->": symbols[name].type = _declared_type(tokens,cursor+2)
114
+ break
86
115
  if word == "signal":
87
116
  var args: Array = []
88
117
  for cursor in range(index+2,mini(index+28,tokens.size()-1)):
@@ -101,12 +130,17 @@ func _declarations(text: String, source: String) -> Dictionary:
101
130
  if index+3<tokens.size() and tokens[index+2].text=="=" and ClassDB.class_exists(tokens[index+3].text): aliases[name] = tokens[index+3].text
102
131
  for cursor in range(index+2,mini(index+7,tokens.size()-2)):
103
132
  if tokens[cursor].text == "preload" and tokens[cursor+1].text == "(" and tokens[cursor+2].kind == "string": aliases[name] = _resolve_path(tokens[cursor+2].text,source)
133
+ if not scoped.has(scope): scoped[scope] = {}
134
+ scoped[scope][name] = symbols[name]
104
135
  # Typed arguments/local declarations also contribute names, never inferred values.
105
136
  for index in range(1,tokens.size()-2):
106
137
  if tokens[index].text == ":" and tokens[index-1].text.is_valid_identifier() and tokens[index+1].text.is_valid_identifier() and tokens[index+1].kind != "keyword" and tokens[index].row == tokens[index+1].row:
107
138
  var name: String = tokens[index-1].text
108
- if not symbols.has(name): symbols[name] = {"type":tokens[index+1].text,"owner":owners.get(tokens[index].row,""),"kind":CodeEdit.KIND_VARIABLE}
109
- return {"symbols":symbols,"aliases":aliases,"base":base,"owners":owners,"required_initializer":required_initializer}
139
+ var scope: String = owners.get(tokens[index].row,"")
140
+ if not scoped.has(scope): scoped[scope] = {}
141
+ if not scoped[scope].has(name): scoped[scope][name] = {"type":_declared_type(tokens,index+1),"owner":scope,"row":tokens[index].row,"block":blocks.get(tokens[index].row,[]),"kind":CodeEdit.KIND_VARIABLE}
142
+ if not symbols.has(name): symbols[name] = scoped[scope][name]
143
+ return {"symbols":symbols,"scoped":scoped,"blocks":blocks,"aliases":aliases,"base":base,"owners":owners,"required_initializer":required_initializer}
110
144
  func _index(text: String, source: String) -> void:
111
145
  if text == _text and source == _path: return
112
146
  _text = text
@@ -114,6 +148,8 @@ func _index(text: String, source: String) -> void:
114
148
  var declarations := _declarations(text,source)
115
149
  _symbols = declarations.symbols
116
150
  _owners = declarations.owners
151
+ _scoped = declarations.scoped
152
+ _blocks = declarations.blocks
117
153
  _aliases = declarations.aliases
118
154
  _base = declarations.base
119
155
  func _script(path: String) -> Dictionary:
@@ -132,25 +168,111 @@ func _method_hint(method: Dictionary) -> String:
132
168
  var args: Array = []
133
169
  for arg in method.get("args",[]): args.append(str(arg.name)+": "+_type_name(arg))
134
170
  return str(method.name)+"("+", ".join(args)+") -> "+_type_name(method.get("return",{}))
171
+ # Bounded cached tokens at the caret. Strings stay opaque; comments and GGX
172
+ # delimiters cannot masquerade as code. Never parse the whole file per request.
173
+ func _chain_tokens(lexical: RefCounted, row: int, column: int) -> Array:
174
+ var result: Array = []
175
+ var budget := 4096
176
+ for line in range(row,maxi(-1,row-16),-1):
177
+ var limit: int = column if line==row else lexical.lines[line].length()
178
+ budget -= limit
179
+ if budget<0: return []
180
+ var tokens: Array = []
181
+ for token in lexical.line(line).tokens:
182
+ if token.start>=limit: break
183
+ if token.kind=="comment": continue
184
+ var item: Dictionary = token.duplicate()
185
+ if item.end>limit: item.text = item.text.left(limit-item.start)
186
+ if item.kind=="string" and not tokens.is_empty() and tokens[-1].kind=="string" and tokens[-1].end==item.start:
187
+ tokens[-1].text += item.text
188
+ tokens[-1].end = item.end
189
+ else: tokens.append(item)
190
+ result = tokens+result
191
+ if result.size()>256: return []
192
+ return result
193
+ func _scope_members(row: int, self_only: bool = false) -> Dictionary:
194
+ var result := _members(_base,_aliases).duplicate()
195
+ result.merge(_scoped.get("",{}),true)
196
+ if not self_only:
197
+ for name in _scoped.get(_owners.get(row,""),{}):
198
+ var item: Dictionary = _scoped[_owners.get(row,"")][name]
199
+ var visible: bool = item.get("row",0)<=row
200
+ for block in item.get("block",[]):
201
+ if not _blocks.get(row,[]).has(block): visible = false
202
+ if visible: result[name] = item
203
+ return result
204
+ func _value_members(value: Dictionary) -> Dictionary:
205
+ if value.get("self",false): return _scope_members(value.row,true)
206
+ var type: String = value.get("type","")
207
+ if type in ["","Variant","void"] or value.get("kind",-1)==CodeEdit.KIND_FUNCTION: return {}
208
+ return _members(type,value.get("aliases",_aliases))
209
+ # Parse only a postfix expression ending at 'end'. Calls skip balanced argument
210
+ # tokens, and use the callable's proven return declaration, never argument values.
211
+ func _chain(tokens: Array, end: int, row: int, depth: int = 0) -> Dictionary:
212
+ if end<0 or depth>=24: return {}
213
+ var token: Dictionary = tokens[end]
214
+ if token.text==")":
215
+ var closes := []
216
+ var opening := -1
217
+ for index in range(end,-1,-1):
218
+ var word: String = tokens[index].text
219
+ if tokens[index].kind=="string": continue
220
+ if word in [")","]","}"]: closes.append(word)
221
+ elif word in ["(","[","{"]:
222
+ if closes.is_empty() or closes.pop_back()!={"(":")","[":"]","{":"}"}[word]: return {}
223
+ if closes.is_empty(): opening = index; break
224
+ if opening<0: return {}
225
+ if opening>0 and (tokens[opening-1].text.is_valid_identifier() and tokens[opening-1].text not in Context.KEYWORDS or tokens[opening-1].text==")"):
226
+ var callable := _chain(tokens,opening-1,row,depth+1)
227
+ if callable.is_empty() or callable.value.get("kind",-1)!=CodeEdit.KIND_FUNCTION: return {}
228
+ var value: Dictionary = callable.value.duplicate()
229
+ value.kind = CodeEdit.KIND_VARIABLE
230
+ return {"start":callable.start,"value":value}
231
+ var grouped := _chain(tokens,end-1,row,depth+1)
232
+ if grouped.is_empty() or grouped.start!=opening+1: return {}
233
+ grouped.start = opening
234
+ return grouped
235
+ if not token.text.is_valid_identifier() or token.kind in ["string","tag","property"]: return {}
236
+ if end>0 and tokens[end-1].text==".":
237
+ var receiver := _chain(tokens,end-2,row,depth+1)
238
+ if receiver.is_empty(): return {}
239
+ var members := _value_members(receiver.value)
240
+ if not members.has(token.text): return {}
241
+ return {"start":receiver.start,"value":members[token.text]}
242
+ if token.text=="self": return {"start":end,"value":{"self":true,"row":row}}
243
+ var scope := _scope_members(row)
244
+ if scope.has(token.text): return {"start":end,"value":scope[token.text]}
245
+ if ClassDB.class_exists(token.text) or _aliases.has(token.text): return {"start":end,"value":{"type":token.text}}
246
+ return {}
247
+ func _receiver_members(tokens: Array, end: int, row: int) -> Dictionary:
248
+ var receiver := _chain(tokens,end,row)
249
+ if receiver.is_empty(): return {}
250
+ # Do not infer from a suffix of an unsupported binary/index/cast expression.
251
+ if receiver.start>0 and tokens[receiver.start-1].text in [".","]","+","-","*","/","%","as","is"]: return {}
252
+ return _value_members(receiver.value)
253
+ func _callable_attribute(lexical: RefCounted, context: Dictionary, row: int, column: int) -> bool:
254
+ if context.frames.is_empty() or context.frames[-1].mode!="tag": return false
255
+ var tokens := _chain_tokens(lexical,row,column)
256
+ for index in range(tokens.size()-1,-1,-1):
257
+ if tokens[index].kind!="expression" or tokens[index].text!="{": continue
258
+ if index<2 or tokens[index-1].text!="=" or tokens[index-2].kind!="property": return false
259
+ var member: Dictionary = _members(context.frames[-1].tag,_aliases).get(tokens[index-2].text,{})
260
+ return member.get("kind",-1)==CodeEdit.KIND_SIGNAL or member.get("type","")=="Callable"
261
+ return false
135
262
  func call_hint(text: String, source: String, lexical: RefCounted, row: int, column: int) -> String:
136
263
  _index(text,source)
137
264
  lexical.update(text)
138
265
  var state: Dictionary = lexical.context(row,column)
139
- if state.suppressed or state.mode != "gd": return ""
140
- var tokens := _tokens(lexical.lines[row].left(column))
266
+ if state.suppressed or state.mode!="gd": return ""
267
+ var tokens := _chain_tokens(lexical,row,column)
141
268
  var depth := 0
142
269
  for index in range(tokens.size()-1,-1,-1):
143
- if tokens[index].text == ")": depth += 1
144
- if tokens[index].text != "(": continue
145
- if depth > 0: depth -= 1; continue
146
- if index == 0: return ""
147
- var name: String = tokens[index-1].text
148
- var members := _members(_base,_aliases)
149
- if index >= 3 and tokens[index-2].text == ".":
150
- var receiver: String = tokens[index-3].text
151
- if receiver != "self": members = _members(str(_symbols.get(receiver,{}).get("type",receiver)),_aliases)
152
- else: members.merge(_symbols,true)
153
- return str(members.get(name,{}).get("hint",""))
270
+ if tokens[index].kind=="string": continue
271
+ if tokens[index].text==")": depth += 1
272
+ if tokens[index].text!="(": continue
273
+ if depth>0: depth -= 1; continue
274
+ var callable := _chain(tokens,index-1,row)
275
+ return str(callable.value.get("hint","")) if not callable.is_empty() and callable.value.get("kind",-1)==CodeEdit.KIND_FUNCTION else ""
154
276
  return ""
155
277
  func _members(type: String, aliases: Dictionary, visited: Array = []) -> Dictionary:
156
278
  var name: String = aliases.get(type,type)
@@ -166,6 +288,9 @@ func _members(type: String, aliases: Dictionary, visited: Array = []) -> Diction
166
288
  result[prop.name] = {"type":_type_name(prop),"kind":CodeEdit.KIND_MEMBER,"value_type":prop.type,"writable":not (int(prop.usage)&PROPERTY_USAGE_READ_ONLY)}
167
289
  for method in ClassDB.class_get_method_list(name): result[method.name] = {"type":_type_name(method.get("return",{})),"kind":CodeEdit.KIND_FUNCTION,"hint":_method_hint(method)}
168
290
  for sig in ClassDB.class_get_signal_list(name): result[sig.name] = {"type":"","kind":CodeEdit.KIND_SIGNAL,"args":sig.args.map(func(arg): return arg.type)}
291
+ # Native return/property identities cannot be redirected by an authored
292
+ # alias that happens to have the same spelling as the native class.
293
+ for member in result.values(): member.aliases = {}
169
294
  _native_cache[name] = result
170
295
  return result
171
296
  if not name.begins_with("res://"):
@@ -187,8 +312,9 @@ func _members(type: String, aliases: Dictionary, visited: Array = []) -> Diction
187
312
  for prop in cached.get_script_property_list():
188
313
  if str(prop.name).is_valid_identifier() and not (int(prop.usage) & (PROPERTY_USAGE_CATEGORY|PROPERTY_USAGE_GROUP|PROPERTY_USAGE_SUBGROUP)): result[prop.name] = {"type":_type_name(prop),"kind":CodeEdit.KIND_MEMBER,"writable":not (int(prop.usage)&PROPERTY_USAGE_READ_ONLY)}
189
314
  for method in cached.get_script_method_list(): result[method.name] = {"type":_type_name(method.get("return",{})),"kind":CodeEdit.KIND_FUNCTION,"hint":_method_hint(method)}
190
- for field in declarations.symbols:
191
- if declarations.symbols[field].owner.is_empty(): result[field] = declarations.symbols[field]
315
+ for field in declarations.scoped.get("",{}):
316
+ result[field] = declarations.scoped[""][field].duplicate()
317
+ result[field].aliases = declarations.aliases
192
318
  return result
193
319
  func _node_type(type: String, aliases: Dictionary, visited: Array = []) -> bool:
194
320
  var name: String = aliases.get(type,type)
@@ -331,6 +457,8 @@ func candidates(text: String, source: String, lexical: RefCounted, row: int, col
331
457
  prefix = left[cursor]+prefix
332
458
  cursor -= 1
333
459
  if context.mode == "tag" and context.closing: prefix = "/"+prefix
460
+ var member_cursor := cursor
461
+ while member_cursor>=0 and left[member_cursor] in [" ","\t"]: member_cursor -= 1
334
462
  var offered: Dictionary = {}
335
463
  if context.mode == "tag":
336
464
  if context.closing:
@@ -363,20 +491,10 @@ func candidates(text: String, source: String, lexical: RefCounted, row: int, col
363
491
  if _node_type(context.tag,_aliases): offered.key = {"kind":CodeEdit.KIND_MEMBER}
364
492
  if members.has("value") and (members.value.get("value_type") == TYPE_BOOL or members.value.get("type") == "bool") and members.has("value_changed") and members.value_changed.get("args",[]).size() == 1 and members.value_changed.args[0] in ["bool",TYPE_BOOL]: offered["bind:value"] = {"kind":CodeEdit.KIND_MEMBER}
365
493
  elif context.mode == "body": return []
366
- elif cursor >= 0 and left[cursor] == ".":
367
- var begin := cursor-1
368
- while begin >= 0 and (left[begin].is_valid_identifier() or left[begin].is_valid_int() or left[begin] == "."): begin -= 1
369
- var receiver := left.substr(begin+1,cursor-begin-1)
370
- var chain := receiver.split(".")
371
- var members: Dictionary = {}
372
- if chain[0] == "self":
373
- for field in _symbols:
374
- if _symbols[field].owner.is_empty(): members[field] = _symbols[field]
375
- if chain[0] == "self": members.merge(_members(_base,_aliases),false)
376
- elif _symbols.has(chain[0]): members = _members(_symbols[chain[0]].type,_aliases)
377
- else: members = _members(chain[0],_aliases)
378
- for index in range(1,chain.size()): members = _members(str(members.get(chain[index],{}).get("type","")),_aliases)
379
- offered = members
494
+ elif member_cursor >= 0 and left[member_cursor] == ".":
495
+ var tokens := _chain_tokens(lexical,row,member_cursor)
496
+ offered = _receiver_members(tokens,tokens.size()-1,row)
497
+
380
498
  else:
381
499
  for word in Context.KEYWORDS: offered[word] = {"kind":CodeEdit.KIND_PLAIN_TEXT}
382
500
  for name in _classes: offered[name] = {"kind":CodeEdit.KIND_CLASS}
@@ -393,11 +511,14 @@ func candidates(text: String, source: String, lexical: RefCounted, row: int, col
393
511
  offered.clear()
394
512
  for name in ["bindable","tool","export","export_range","onready","warning_ignore"]: offered[name] = {"kind":CodeEdit.KIND_PLAIN_TEXT}
395
513
  var result: Array = []
514
+ var callable_attribute: bool = context.mode=="gd" and _callable_attribute(lexical,context,row,column)
396
515
  for name in offered:
397
516
  if (str(name).begins_with(prefix) or offered[name].has("match")) and (not str(name).begins_with("_") or prefix.begins_with("_") or _symbols.has(name)):
398
517
  var item: Dictionary = offered[name]
399
518
  var insert: String = item.get("insert",str(name).trim_prefix("bind:") if prefix.begins_with("bind:") else str(name))
400
- var display: String = str(name) if item.has("import") else (insert+" — "+str(item.origin) if item.has("origin") else insert)
519
+ if context.mode=="gd" and member_cursor>=0 and left[member_cursor]=="." and item.kind==CodeEdit.KIND_FUNCTION and not callable_attribute and not lexical.lines[row].substr(column).strip_edges().begins_with("("):
520
+ insert += "()"
521
+ var display: String = str(name) if item.has("import") else (str(name)+" — "+str(item.origin) if item.has("origin") else str(name))
401
522
  if context.mode == "tag" and not item.has("import") and ClassDB.class_exists(insert): display += " — Godot "+ClassDB.get_parent_class(insert)
402
523
  result.append({"text":display,"insert":insert,"kind":item.kind,"row":row,"start":cursor if context.mode == "tag" and context.closing else cursor+1,"column":column,"hint":item.get("hint",""),"imports":[item["import"]] if item.has("import") else []})
403
524
  result.sort_custom(func(a,b): return a.text < b.text)
@@ -3,5 +3,5 @@
3
3
  name="Estragon"
4
4
  description="Native Gogo/GGX highlighting, compilation and validation before Play."
5
5
  author="Resist Design"
6
- version="0.1.0-beta.11"
6
+ version="0.1.0-beta.13"
7
7
  script="plugin.gd"
@@ -3,8 +3,11 @@ const Profile = preload("profile.tres")
3
3
  ## F01 computation and retained static-shape records external to native objects.
4
4
  const Binding = preload("binding.gd")
5
5
  const Element = preload("element.gd")
6
+ const Hosts = preload("../node/internal/composition_hosts.tres")
6
7
  class Mounted extends RefCounted:
7
8
  var node: WeakRef
9
+ var id: int
10
+ var borrowed: WeakRef
8
11
  var type: Variant
9
12
  var key: Variant
10
13
  var keyed := false
@@ -14,6 +17,10 @@ class Mounted extends RefCounted:
14
17
  var bindings: Dictionary = {}
15
18
  var children: Array = []
16
19
  var host: WeakRef
20
+ var projection
21
+ var _borrow_seen: Dictionary = {}
22
+ var _observes_children := false
23
+ var layout_host
17
24
  var state: WeakRef
18
25
  var parent_computation: WeakRef
19
26
  var mounted: Mounted
@@ -32,6 +39,8 @@ var _consecutive := 0
32
39
  func _init(owner: Node, manager: Resource) -> void:
33
40
  host = weakref(owner)
34
41
  state = weakref(manager)
42
+ projection = preload("projection.gd").new(self,owner)
43
+ layout_host = preload("layout_host.gd").new(owner)
35
44
  var ancestor := owner.get_parent()
36
45
  while ancestor != null:
37
46
  if manager.records.has(ancestor.get_instance_id()):
@@ -58,10 +67,14 @@ func depth() -> int:
58
67
  return result
59
68
  func suspend() -> void:
60
69
  active = false
70
+ projection.stop()
71
+ Hosts.replace_projection(self,{}, {})
72
+ layout_host.stop()
61
73
  _disconnect_bindings(mounted)
62
74
  _disconnect()
63
75
  func resume() -> void:
64
76
  active = true
77
+ layout_host.start()
65
78
  schedule()
66
79
  func _disconnect() -> void:
67
80
  for pair in subscriptions.values():
@@ -100,16 +113,27 @@ func _flush() -> void:
100
113
  var desired = owner.call("build_view")
101
114
  var reads: Dictionary = manager.finish()
102
115
  if Profile.is_enabled(): Profile.elapsed("view",started)
116
+ _borrow_seen.clear()
117
+ _observes_children = false
103
118
  desired = _normalize(desired)
104
119
  _rendering = false
105
120
  if not desired is Element or not _valid(desired,mounted) or not _preflight(desired,mounted,owner) or not _rescue_clear(desired,mounted,owner):
106
121
  push_error("Invalid composition output or foreign boundary conflict; previous tree retained")
107
122
  return
123
+ # A nested array may be an empty get_children() result. Observe native
124
+ # changes without inspecting the expression source or polling the tree.
125
+ if _observes_children: projection.start()
126
+ else: projection.stop()
108
127
  _subscribe(reads)
109
128
  # Catch mutation after a read during first composition/commit as a later
110
129
  # pass. Source-side effects are unsupported, but never recurse into SceneTree.
111
130
  _rendering = true
112
131
  mounted = _reconcile(desired,mounted,owner,owner)
132
+ var projected := {}
133
+ var ordering := {}
134
+ _projection_tree(mounted,projected,ordering)
135
+ Hosts.replace_projection(self,projected,ordering)
136
+ layout_host.update(mounted.node.get_ref() if mounted != null else null)
113
137
  _rendering = false
114
138
  runs += 1
115
139
  if Profile.is_enabled(): Profile.elapsed("computation",started)
@@ -141,8 +165,26 @@ func _flatten(values: Array, path: Array, output: Array, ancestors: Array, level
141
165
  slot.append(index)
142
166
  var value = values[index]
143
167
  if value is Array:
168
+ _observes_children = true
144
169
  if not _flatten(value,slot,output,ancestors,level+1): return false
145
170
  elif value==null: output.append(null)
171
+ elif value is Node:
172
+ _observes_children = true
173
+ var manager = state.get_ref()
174
+ if manager.is_managed(value): continue
175
+ if value.get_parent() != host.get_ref():
176
+ var label: String = str(value.get_path()) if value.is_inside_tree() else str(value.name)
177
+ push_error(ancestors.back().source+": GGX borrowed children must be persistent direct children of the rendering host: "+label)
178
+ return false
179
+ if value.owner == null: continue # Foreign runtime actors remain native.
180
+ if _borrow_seen.has(value.get_instance_id()):
181
+ push_error(ancestors.back().source+": GGX scene child referenced more than once: "+str(value.get_path()))
182
+ return false
183
+ _borrow_seen[value.get_instance_id()] = true
184
+ var child := Element.new()
185
+ child.borrowed = weakref(value)
186
+ child.slot = slot
187
+ output.append(child)
146
188
  else:
147
189
  var child = _normalize(value,ancestors,level+1)
148
190
  if child==null: return false
@@ -151,6 +193,7 @@ func _flatten(values: Array, path: Array, output: Array, ancestors: Array, level
151
193
  return true
152
194
  # Exact key type participates in identity (bool/float never alias int).
153
195
  func _identity(value, index: int) -> String:
196
+ if value.borrowed != null: return "n:"+str(value.borrowed.get_ref().get_instance_id()) if value.borrowed.get_ref() != null else "expired"
154
197
  if value.keyed: return "k:"+str(typeof(value.key))+":"+str(value.key)
155
198
  return "p:"+str(value.slot if not value.slot.is_empty() else [index])
156
199
  func _matches(desired: Array, previous: Array) -> Array:
@@ -163,6 +206,7 @@ func _matches(desired: Array, previous: Array) -> Array:
163
206
  return result
164
207
  func _valid(desired: Element, previous: Mounted) -> bool:
165
208
  if Profile.is_enabled(): Profile.add("validations")
209
+ if desired.borrowed != null: return desired.borrowed.get_ref() != null
166
210
  if desired.type == null: return false
167
211
  if desired.type is String:
168
212
  if not ClassDB.class_exists(desired.type) or not ClassDB.is_parent_class(desired.type,"Node") or not ClassDB.can_instantiate(desired.type): return false
@@ -189,7 +233,7 @@ func _valid(desired: Element, previous: Mounted) -> bool:
189
233
  names[name] = true
190
234
  return true
191
235
  func _collect_foreign(record, result: Array) -> void:
192
- if record==null: return
236
+ if record==null or record.borrowed != null: return
193
237
  var node = record.node.get_ref()
194
238
  if node==null: return
195
239
  var known: Array = []
@@ -238,10 +282,16 @@ func _boundary_clear(desired: Element, parent: Node) -> bool:
238
282
  return true
239
283
  func _mount(desired: Element, parent: Node, owner: Node) -> Mounted:
240
284
  var record := Mounted.new()
285
+ if desired.borrowed != null:
286
+ record.borrowed = desired.borrowed
287
+ record.node = desired.borrowed
288
+ return record
241
289
  var node: Node = ClassDB.instantiate(desired.type) if desired.type is String else desired.type.new()
290
+ state.get_ref().managed[node.get_instance_id()] = weakref(node)
242
291
  allocations += 1
243
292
  if Profile.is_enabled(): Profile.add("nodes_created")
244
293
  record.node = weakref(node)
294
+ record.id = node.get_instance_id()
245
295
  record.type = desired.type
246
296
  record.key = desired.key
247
297
  record.keyed = desired.keyed
@@ -284,6 +334,9 @@ func _apply(desired: Element, record: Mounted) -> void:
284
334
  record.properties = desired.properties.duplicate()
285
335
  record.handlers = desired.handlers.duplicate()
286
336
  func _compatible(desired: Element, record: Mounted) -> bool:
337
+ if record == null: return false
338
+ if desired.borrowed != null or record.borrowed != null:
339
+ return desired.borrowed != null and record.borrowed != null and desired.borrowed.get_ref() != null and desired.borrowed.get_ref() == record.node.get_ref()
287
340
  return record != null and is_same(record.type,desired.type) and record.keyed==desired.keyed and (not desired.keyed or typeof(record.key)==typeof(desired.key) and record.key==desired.key) and record.node.get_ref()!=null
288
341
  func _reconcile(desired, record, parent: Node, owner: Node):
289
342
  if Profile.is_enabled(): Profile.add("reconciles")
@@ -293,6 +346,7 @@ func _reconcile(desired, record, parent: Node, owner: Node):
293
346
  if not _compatible(desired,record):
294
347
  if record != null: _free_managed(record,owner)
295
348
  return _mount(desired,parent,owner)
349
+ if record.borrowed != null: return record
296
350
  _apply(desired,record)
297
351
  var node: Node = record.node.get_ref()
298
352
  if node.get_parent()!=parent:
@@ -340,7 +394,7 @@ func _prepare_names(desired: Array, matches: Array, parent: Node) -> void:
340
394
  func _order(children: Array, parent: Node) -> void:
341
395
  var nodes: Array = []
342
396
  for child in children:
343
- if child!=null: nodes.append(child.node.get_ref())
397
+ if child!=null and child.borrowed == null: nodes.append(child.node.get_ref())
344
398
  # Native child indices are unique. Binary-search minimal tails to recover
345
399
  # one longest increasing subsequence without quadratic comparisons.
346
400
  var tails: Array = []
@@ -381,6 +435,7 @@ func _order(children: Array, parent: Node) -> void:
381
435
  func _preflight(desired, previous, parent: Node, contracts: Variant = null) -> bool:
382
436
  if Profile.is_enabled(): Profile.add("preflights")
383
437
  if desired == null: return true
438
+ if desired.borrowed != null: return desired.borrowed.get_ref() != null
384
439
  # Cache only within this synchronous desired-tree validation. No Script
385
440
  # contracts survive a commit or hide editor reload/metadata changes.
386
441
  if contracts==null: contracts = {}
@@ -432,7 +487,7 @@ func _preflight(desired, previous, parent: Node, contracts: Variant = null) -> b
432
487
  var matches := _matches(desired.children,previous.children if node!=null else [])
433
488
  for index in range(desired.children.size()):
434
489
  var child = desired.children[index]
435
- if child == null: continue
490
+ if child == null or child.borrowed != null: continue
436
491
  var old = matches[index]
437
492
  if not _preflight(child,old,null,contracts): return false
438
493
  var name: String = str(child.properties.get("name",str(old.node.get_ref().name) if old!=null and _compatible(child,old) else ""))
@@ -444,10 +499,13 @@ func _preflight(desired, previous, parent: Node, contracts: Variant = null) -> b
444
499
  if str(existing.name)==name and not known.has(existing): return false
445
500
  return true
446
501
  func _free_managed(record: Mounted, rescue: Node = null) -> void:
502
+ if record.borrowed != null: return
447
503
  for child in record.children:
448
504
  if child != null: _free_managed(child,rescue)
449
505
  var node = record.node.get_ref()
450
- if node == null: return
506
+ if node == null:
507
+ state.get_ref().managed.erase(record.id)
508
+ return
451
509
  for binding in record.bindings.values(): binding.disconnect_edit()
452
510
  record.bindings.clear()
453
511
  # Foreign descendants have no record. Move them outside the managed region
@@ -461,7 +519,9 @@ func _free_managed(record: Mounted, rescue: Node = null) -> void:
461
519
  if owner != null:
462
520
  owner.add_child(child)
463
521
  if persisted_owner != null and persisted_owner.is_ancestor_of(child): child.owner = persisted_owner
522
+ var id: int = node.get_instance_id()
464
523
  node.free()
524
+ if manager != null: manager.managed.erase(id)
465
525
  frees += 1
466
526
  if Profile.is_enabled(): Profile.add("nodes_freed")
467
527
  func dispose(remove_nodes: bool, rescue: Node = null) -> void:
@@ -469,9 +529,32 @@ func dispose(remove_nodes: bool, rescue: Node = null) -> void:
469
529
  disposed = true
470
530
  suspend()
471
531
  if remove_nodes and mounted != null: _free_managed(mounted,rescue)
532
+ _unindex(mounted)
472
533
  mounted = null
473
534
 
474
535
  func _disconnect_bindings(record) -> void:
475
536
  if record==null: return
476
537
  for binding in record.bindings.values(): binding.disconnect_edit()
477
538
  for child in record.children: _disconnect_bindings(child)
539
+
540
+ func _projection_tree(record, projected: Dictionary, ordering: Dictionary) -> void:
541
+ if record == null or record.borrowed != null: return
542
+ var parent = record.node.get_ref()
543
+ if parent == null: return
544
+ var nodes: Array = []
545
+ var has_borrowed := false
546
+ for child in record.children:
547
+ if child == null: continue
548
+ var node = child.node.get_ref()
549
+ if node == null: continue
550
+ nodes.append(weakref(node))
551
+ if child.borrowed != null:
552
+ projected[node.get_instance_id()] = [node,parent]
553
+ has_borrowed = true
554
+ else: _projection_tree(child,projected,ordering)
555
+ if has_borrowed: ordering[parent.get_instance_id()] = nodes
556
+
557
+ func _unindex(record) -> void:
558
+ if record == null or record.borrowed != null: return
559
+ state.get_ref().managed.erase(record.id)
560
+ for child in record.children: _unindex(child)
@@ -2,6 +2,8 @@
2
2
  extends RefCounted
3
3
  const Profile = preload("profile.tres")
4
4
  ## Desired values only. No native Node is allocated during description creation.
5
+ # Internal normalized weak reference, only populated by child normalization.
6
+ var borrowed: WeakRef
5
7
  var type: Variant
6
8
  var properties: Dictionary
7
9
  var bindings: Dictionary = {}
@@ -0,0 +1,58 @@
1
+ extends RefCounted
2
+ ## One transparent managed-root bridge owned by an existing Computation.
3
+ ## No user fields, metadata, helper Node, authored-child adoption or layout math.
4
+ const Coordinator = preload("../node/internal/coordinator.gd")
5
+ const Hosts = preload("../node/internal/composition_hosts.tres")
6
+ var host: WeakRef
7
+ var root: WeakRef
8
+ var layout
9
+ var target
10
+ func _init(owner: Node) -> void:
11
+ host = weakref(owner)
12
+ # Native participants/entries already own a coordinator. Never duplicate it.
13
+ if owner.has_method("_get_layout_coordinator"): return
14
+ var dimension := 2 if owner is Node2D else (3 if owner is Node3D else 0)
15
+ if dimension == 0: return
16
+ layout = Coordinator.new(owner,dimension,Coordinator.Mode.COMPOSITION)
17
+ start()
18
+ func start() -> void:
19
+ if layout == null or layout.active: return
20
+ var owner = host.get_ref()
21
+ Hosts.add(owner,layout)
22
+ layout.start()
23
+ update(root.get_ref() if root != null else null)
24
+ func stop() -> void:
25
+ if layout == null or not layout.active: return
26
+ var owner = host.get_ref()
27
+ _disconnect()
28
+ # Keep registry identity until stop detaches the model from its parent;
29
+ # active=false already prevents other coordinators from adopting it.
30
+ layout.stop()
31
+ Hosts.remove(owner,layout)
32
+ func order_moved() -> void:
33
+ if layout != null and layout.active: layout.order_moved()
34
+ func _disconnect() -> void:
35
+ if target != null and target.model.invalidated.is_connected(_configure): target.model.invalidated.disconnect(_configure)
36
+ target = null
37
+ func update(view: Node) -> void:
38
+ root = weakref(view) if view != null else null
39
+ if layout == null or not layout.active: return
40
+ _disconnect()
41
+ layout.managed_root = root
42
+ target = layout.participant(view,true)
43
+ if target != null and target._mode == Coordinator.Mode.ENTRY: target = null
44
+ if target != null: target.model.invalidated.connect(_configure)
45
+ layout._sync()
46
+ _configure()
47
+ func _configure() -> void:
48
+ if layout == null or not layout.active: return
49
+ var requested := Vector3(-1,-1,0) if layout._dimension==2 else Vector3(-1,-1,-1)
50
+ var fills := Vector3.ZERO
51
+ var included: bool = target != null and (target._mode != Coordinator.Mode.CONTROL or target.control_adapter.participates())
52
+ if included:
53
+ requested = target.model.requested
54
+ fills = target.model.fill
55
+ layout.model.allocation_minimum = target.model.allocation_minimum if included else Vector3.ZERO
56
+ # One child, at zero local offset. Parent places the native host once;
57
+ # root constraints determine both proxy allocation and root allocation.
58
+ layout.model.configure(requested,0,false,0,fills)
@@ -0,0 +1 @@
1
+ uid://dv8wymdhyov8f