@papercraftgames/estragon 0.1.0-beta.35 → 0.1.0-beta.36

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.
@@ -16,6 +16,12 @@ func apply(value: Model.Module) -> void:
16
16
  _class_scope(module.parts)
17
17
  if not file.diagnostics.is_empty(): return
18
18
  _collect(module.parts)
19
+ module.data_shape = class_marker!=null
20
+ if module.data_shape:
21
+ for name in ["to_data","_gogo_data_changed"]:
22
+ if members.has(name):
23
+ file.fail("Gogo data shape reserves "+name,members[name].start.index)
24
+ return
19
25
  module.parts.assign(_parts(module.parts))
20
26
  # A class marker is unambiguous only in the script preamble, directly
21
27
  # before extends/class_name. Existing preceding-line property markers stay so.
@@ -0,0 +1,210 @@
1
+ @tool
2
+ extends RefCounted
3
+ ## Lexer/span typed-data boundaries. Ordinary .gd is never rewritten.
4
+ const Model = preload("model.gd")
5
+ const Lexer = preload("lexer.gd")
6
+ const Resolver = preload("native/resolver.gd")
7
+ var file
8
+ var module
9
+ var aliases := {}
10
+ var declarations: Array = []
11
+ var lexical
12
+ func _init(source): file = source
13
+ func apply(value) -> void:
14
+ module = value
15
+ lexical = preload("layouts.gd").new(file)
16
+ lexical.module = preload("parser.gd").new(file).parse()
17
+ lexical._index()
18
+ if module.data_shape:
19
+ var tokens: Array = lexical.tokens
20
+ for index in range(tokens.size()-5):
21
+ if tokens[index].text!="func" or tokens[index+1].text!="_notification" or tokens[index].span.start.column!=1: continue
22
+ var colon := index+4
23
+ while colon<tokens.size() and tokens[colon].text!=")": colon += 1
24
+ while colon<tokens.size() and tokens[colon].text!=":": colon += 1
25
+ if colon+1>=tokens.size(): continue
26
+ var parameter: String = tokens[index+3].text
27
+ module.data_notification = true
28
+ module.data_type_edits.append({"span":file.span(tokens[colon].span.end.index,tokens[colon+1].span.start.index),"value":"\n"+module.indentation+"if "+parameter+"==NOTIFICATION_PREDELETE: preload(%s).prune()\n"%var_to_str(preload("source.gd").relative_path(file.generated_path().get_base_dir(),preload("../runtime/data/state.tres").resource_path))+module.indentation})
29
+ var resolver := Resolver.new(file)
30
+ resolver.scan(module)
31
+ for name in resolver.aliases:
32
+ if _shape_import(resolver.aliases[name]): aliases[name] = true
33
+ for index in range(lexical.tokens.size()-1):
34
+ if lexical.tokens[index].text!="extends": continue
35
+ var base = lexical.tokens[index+1]
36
+ if aliases.has(base.text): module.data_inherited = true
37
+ elif base.kind=="string":
38
+ var path = str_to_var(base.text)
39
+ if path is String:
40
+ if not path.is_absolute_path(): path = file.generated_path().get_base_dir().path_join(path).simplify_path()
41
+ module.data_inherited = _shape_import(path)
42
+ if module.identifiers.has("_GogoArrayCollection"):
43
+ file.fail("Reserved Gogo data type name _GogoArrayCollection",0)
44
+ return
45
+ for part in module.parts:
46
+ if part is Model.Bindable:
47
+ part.data_type = descriptor(part.type_name)
48
+ if not part.data_type.is_empty():
49
+ module.data_types[part.name] = part.data_type
50
+ if aliases.has(part.type_name) or part.type_name.begins_with("ArrayCollection["):
51
+ declarations.append({"name":part.name,"type":part.data_type,"offset":part.name_span.start.index})
52
+ if part.type_name.begins_with("ArrayCollection") and part.data_type.is_empty():
53
+ file.fail("ArrayCollection requires one supported typed data element",part.type_span.start.index,part.type_span.end.index)
54
+ return
55
+ if part.type_name.begins_with("ArrayCollection["): _collection_type(part.type_span)
56
+ var tokens: Array = lexical.tokens
57
+ for symbol in lexical.symbols:
58
+ var index := -1
59
+ for cursor in range(tokens.size()):
60
+ if tokens[cursor].span.start.index==symbol.span.start.index: index = cursor; break
61
+ if index<0 or index+2>=tokens.size() or tokens[index+1].text!=":": continue
62
+ var end := index+2
63
+ var depth := 0
64
+ while end+1<tokens.size():
65
+ if tokens[end].text=="[": depth += 1
66
+ elif tokens[end].text=="]": depth -= 1
67
+ if depth==0 and tokens[end+1].text!="[": break
68
+ end += 1
69
+ var type_span = file.span(tokens[index+2].span.start.index,tokens[end].span.end.index)
70
+ var type := descriptor(file.slice(type_span))
71
+ if type.is_empty() or not (aliases.has(file.slice(type_span)) or file.slice(type_span).begins_with("ArrayCollection[")): continue
72
+ declarations.append({"name":symbol.name,"type":type,"offset":symbol.span.start.index})
73
+ if symbol.scope==0: module.data_types[symbol.name] = type
74
+ if file.slice(type_span).begins_with("ArrayCollection["): _collection_type(type_span)
75
+ # Godot 4.0's statically typed custom-iterator fast path passes/clobbers
76
+ # iterator state differently from Variant iteration. Keep Gogo iteration on
77
+ # the public Variant protocol, including independent nested iterators.
78
+ for index in range(tokens.size()-3):
79
+ if tokens[index].text!="for" or tokens[index+2].text!="in": continue
80
+ var end := index+3
81
+ var depth := 0
82
+ while end<tokens.size():
83
+ if tokens[end].text in ["(","[","{"]: depth += 1
84
+ elif tokens[end].text in [")","]","}"]: depth -= 1
85
+ if depth==0 and tokens[end].text==":": break
86
+ end += 1
87
+ if end>=tokens.size(): continue
88
+ var span = file.span(tokens[index+3].span.start.index,tokens[end].span.start.index)
89
+ var root: String = tokens[index+3].text
90
+ var type := _type(root,span.start.index)
91
+ if root=="self" and index+5<end and tokens[index+4].text==".": type = _type(tokens[index+5].text,span.start.index,true)
92
+ if type.is_empty(): continue
93
+ module.data_type_edits.append({"span":span,"value":"preload(%s).iterate(%s)"%[var_to_str(preload("source.gd").relative_path(file.generated_path().get_base_dir(),preload("../runtime/data/state.tres").resource_path)),file.slice(span)]})
94
+ module.parts.assign(_rewrite(module.parts))
95
+ for part in module.parts:
96
+ if not part is Model.Bindable or part.data_type.is_empty(): continue
97
+ var declaration := _tokens([_code(part.declaration_span)])
98
+ for index in range(declaration.size()):
99
+ if declaration[index].text!="=" or not (part.type_name.begins_with("ArrayCollection[") or aliases.has(part.type_name)): continue
100
+ part.initializer = Model.GdExpression.new()
101
+ part.initializer.span = file.span(declaration[index+1].span.start.index,part.declaration_span.end.index)
102
+ part.initializer.parts.assign([_code(part.initializer.span)])
103
+ part.declaration_span = file.span(part.declaration_span.start.index,declaration[index+1].span.start.index)
104
+ break
105
+ func _shape_import(path: String) -> bool:
106
+ var authored := path.get_base_dir().get_base_dir().path_join(path.get_file().get_basename()+".gogo")
107
+ if not FileAccess.file_exists(authored): return false
108
+ var text = file.project.read(file.project.authored(authored)) if file.project!=null else FileAccess.get_file_as_string(authored)
109
+ var source = preload("source.gd").new(text,authored)
110
+ var imported = preload("parser.gd").new(source).parse()
111
+ if imported==null: return false
112
+ preload("bindable.gd").new(source).apply(imported)
113
+ return imported.data_shape
114
+ func descriptor(type: String) -> String:
115
+ type = type.strip_edges()
116
+ if type.begins_with("Array[") and type.ends_with("]"):
117
+ var element := descriptor(type.substr(6,type.length()-7))
118
+ return '{"array": '+element+'}' if not element.is_empty() else ""
119
+ if type.begins_with("ArrayCollection[") and type.ends_with("]"):
120
+ var element := descriptor(type.substr(16,type.length()-17))
121
+ return "["+element+"]" if not element.is_empty() else ""
122
+ if aliases.has(type): return module.import_aliases.get(type,type)
123
+ var primitive := {"bool":"TYPE_BOOL","int":"TYPE_INT","float":"TYPE_FLOAT","String":"TYPE_STRING","Array":"TYPE_ARRAY","Dictionary":"TYPE_DICTIONARY"}
124
+ return primitive.get(type,"")
125
+ func _collection_type(span) -> void:
126
+ module.data_type_edits.append({"span":span,"value":"_GogoArrayCollection"})
127
+ func _tokens(parts: Array) -> Array:
128
+ var result: Array = []
129
+ for part in parts:
130
+ if part is Model.RenderCall: result.append_array(_tokens(part.original))
131
+ elif part is Model.Code:
132
+ var lexer := Lexer.new(file)
133
+ var cursor: int = part.span.start.index
134
+ while cursor<part.span.end.index:
135
+ var token = lexer.next_token(cursor)
136
+ if token==null: break
137
+ cursor = token.span.end.index
138
+ if token.kind not in ["whitespace","newline","comment","continuation"]: result.append(token)
139
+ return result
140
+ func _code(span):
141
+ var code := Model.Code.new()
142
+ code.span = span
143
+ return code
144
+ func _slice(parts: Array, start: int, end: int) -> Array:
145
+ var output: Array = []
146
+ for part in parts:
147
+ if part.span.end.index<=start or part.span.start.index>=end: continue
148
+ output.append(_code(file.span(maxi(start,part.span.start.index),mini(end,part.span.end.index))) if part is Model.Code else part)
149
+ return output
150
+ func _type(name: String, offset: int, own: bool = false) -> String:
151
+ var scope: int = 0 if own else lexical._scope(offset)
152
+ while scope>=0:
153
+ var selected = null
154
+ for symbol in lexical.symbols:
155
+ if symbol.name==name and symbol.scope==scope and (symbol.span.start.index<=offset or scope==0) and (selected==null or symbol.span.start.index>selected.span.start.index): selected = symbol
156
+ if selected!=null:
157
+ for declaration in declarations:
158
+ if declaration.offset==selected.span.start.index: return declaration.type
159
+ return ""
160
+ scope = lexical.scopes[scope].parent
161
+ return ""
162
+ func _rewrite(parts: Array) -> Array:
163
+ for part in parts:
164
+ if part is Model.GdExpression: part.parts.assign(_rewrite(part.parts))
165
+ elif part is Model.Component:
166
+ for attribute in part.attributes:
167
+ if attribute.value is Model.GdExpression: attribute.value.parts.assign(_rewrite(attribute.value.parts))
168
+ part.children.assign(_rewrite(part.children))
169
+ var tokens := _tokens(parts)
170
+ var writes: Array = []
171
+ for index in range(1,tokens.size()-1):
172
+ if tokens[index].text!="=": continue
173
+ var start := index-1
174
+ while start>0 and tokens[start-1].span.start.line==tokens[index].span.start.line and tokens[start-1].text!=";": start -= 1
175
+ if tokens[start].text!="var":
176
+ for cursor in range(start,index):
177
+ if tokens[cursor].text==":": start = cursor+1
178
+ var declaration: bool = tokens[start].text=="var"
179
+ var name: String = tokens[start+1].text if declaration else tokens[start].text
180
+ var type := _type(name,tokens[index].span.start.index)
181
+ if name=="self" and start+2<index: type = _type(tokens[start+2].text,tokens[index].span.start.index,true)
182
+ if type.is_empty(): continue
183
+ var end := index+1
184
+ var depth := 0
185
+ while end<tokens.size():
186
+ if depth==0 and (tokens[end].text==";" or end>index+1 and tokens[end].span.start.line>tokens[end-1].span.end.line): break
187
+ if tokens[end].text in ["(","[","{"]: depth += 1
188
+ elif tokens[end].text in [")","]","}"]: depth -= 1
189
+ end += 1
190
+ var write := Model.DataWrite.new()
191
+ write.span = file.span(tokens[start].span.start.index,tokens[end-1].span.end.index)
192
+ write.expression.assign(_slice(parts,tokens[index+1].span.start.index,write.span.end.index))
193
+ if not declaration and tokens[index-2].text==".":
194
+ write.field = tokens[index-1].text
195
+ write.owner.assign(_slice(parts,tokens[start].span.start.index,tokens[index-2].span.start.index))
196
+ else:
197
+ write.prefix.assign(_slice(parts,write.span.start.index,tokens[index+1].span.start.index))
198
+ write.descriptor = type
199
+ write.previous = "null" if declaration else name
200
+ writes.append(write)
201
+ if parts.is_empty(): return parts
202
+ var output: Array = []
203
+ var cursor: int = parts[0].span.start.index
204
+ for write in writes:
205
+ if write.span.start.index<cursor: continue
206
+ output.append_array(_slice(parts,cursor,write.span.start.index))
207
+ output.append(write)
208
+ cursor = write.span.end.index
209
+ output.append_array(_slice(parts,cursor,parts[-1].span.end.index))
210
+ return output
@@ -0,0 +1 @@
1
+ uid://bv0ktwkqpayt7
@@ -5,6 +5,8 @@ const Preset = preload("../runtime/composition/preset.gd")
5
5
  const Element = preload("../runtime/composition/element.gd")
6
6
  const State = preload("../runtime/composition/state.tres")
7
7
  const Binding = preload("../runtime/composition/binding.gd")
8
+ const Data = preload("../runtime/data/state.tres")
9
+ const Collection = preload("../runtime/data/array_collection.gd")
8
10
  const Model = preload("model.gd")
9
11
  const Source = preload("source.gd")
10
12
  const MappedWriter = preload("source_map.gd")
@@ -57,6 +59,15 @@ func _resource(resource: Resource) -> String:
57
59
 
58
60
  func emit() -> MappedWriter:
59
61
  _parts(_module.parts)
62
+ if _module.data_type_edits.any(func(edit): return edit.value=="_GogoArrayCollection"): _writer.append("const _GogoArrayCollection = preload("+_resource(Collection)+")\n")
63
+ if _module.data_shape and not _module.data_inherited: _writer.append("signal _gogo_data_changed\n")
64
+ if _module.data_shape:
65
+ _writer.append("\nconst _GOGO_DATA_SHAPE_"+_file.name.sha256_text().substr(0,16)+" = true\n")
66
+ _writer.append("\nfunc to_data():\n"+_module.indentation+"return preload("+_resource(Data)+").to_data(self)\n")
67
+ if not _module.data_types.is_empty():
68
+ _writer.append("\nconst _GOGO_DATA_TYPES_"+_file.name.sha256_text().substr(0,16)+" = {")
69
+ for name in _module.data_types: _writer.append(_string(name)+": "+_module.data_types[name]+",")
70
+ _writer.append("}\n")
60
71
  var metadata := "_GOGO_RENDER_FUNCTIONS_"+_file.name.sha256_text().substr(0,16)
61
72
  while _module.identifiers.has(metadata): metadata += "_"
62
73
  _writer.append("\nconst "+metadata+" = "+var_to_str({"reactive":_module.render_functions,"ordinary":_module.ordinary_functions}))
@@ -82,8 +93,10 @@ func emit() -> MappedWriter:
82
93
  _writer.append("\nfunc "+method.name+"(): return ",method.binding.span)
83
94
  _default_groups(method.binding)
84
95
  _writer.append("\n",method.binding.span)
85
- if _module.composition:
86
- _writer.append("\nfunc _notification(_gogo_what: int) -> void:\n"+_module.indentation+"preload("+_resource(State)+").lifecycle(self, _gogo_what)\n")
96
+ if _module.composition or _module.data_shape and not _module.data_notification:
97
+ _writer.append("\nfunc _notification(_gogo_what: int) -> void:\n")
98
+ if _module.composition: _writer.append(_module.indentation+"preload("+_resource(State)+").lifecycle(self, _gogo_what)\n")
99
+ if _module.data_shape: _writer.append(_module.indentation+"if _gogo_what==NOTIFICATION_PREDELETE: preload("+_resource(Data)+").prune()\n")
87
100
  if not _factories.is_empty():
88
101
  _writer.append("\n\nclass " + _factory_class + ":", _factories[0].root.span)
89
102
  _writer.append("\n"+_module.indentation+"const "+_element_class+" = preload("+_resource(Element)+")\n")
@@ -151,12 +164,14 @@ func _parts(parts: Array[Model.SyntaxNode]) -> void:
151
164
  elif part is Model.Bindable: _bindable(part)
152
165
  elif part is Model.Layout: _layout(part)
153
166
  elif part is Model.RenderCall: _render_call(part)
167
+ elif part is Model.DataWrite: _data_write(part)
154
168
  elif part is Model.Literal and part.kind=="preset-reference": _writer.append(str(part.value),part.span)
155
169
  else: _call(part)
156
170
 
157
171
  func _code(span: Model.Span) -> void:
158
172
  var cursor: int = span.start.index
159
173
  var edits: Array = []
174
+ edits.append_array(_module.data_type_edits)
160
175
  for imported in _module.resource_imports:
161
176
  edits.append({"span":imported.span,"value":_string(Source.relative_path(_output_directory,imported.path))})
162
177
  for imported in _module.identifier_imports: edits.append({"span":imported.span,"value":imported.alias})
@@ -171,6 +186,24 @@ func _code(span: Model.Span) -> void:
171
186
  var rest := _file.span(cursor,span.end.index)
172
187
  _writer.append(_file.slice(rest),rest,true)
173
188
 
189
+ func _data_write(write: Model.DataWrite) -> void:
190
+ var location := _string("%s:%d:%d"%[_file.name,write.span.start.line,write.span.start.column])
191
+ if not write.field.is_empty():
192
+ _writer.append("preload("+_resource(Data)+").assign(",write.span)
193
+ _parts(write.owner)
194
+ _writer.append(", "+_string(write.field)+", ",write.span)
195
+ _parts(write.expression)
196
+ _writer.append(", "+location+", func(): ",write.span)
197
+ _parts(write.owner)
198
+ _writer.append("."+write.field+" = ",write.span)
199
+ _parts(write.owner)
200
+ _writer.append("."+write.field+")",write.span)
201
+ else:
202
+ _parts(write.prefix)
203
+ _writer.append("preload("+_resource(Data)+").value(",write.span)
204
+ _parts(write.expression)
205
+ _writer.append(", "+write.descriptor+", "+write.previous+", "+location+")",write.span)
206
+
174
207
  func _call(node: Model.Component) -> void:
175
208
  var factory := Factory.new()
176
209
  while true:
@@ -319,6 +352,10 @@ func _bindable(property: Model.Bindable) -> void:
319
352
  if property.annotations_span != null:
320
353
  _writer.append(_file.slice(property.annotations_span),property.annotations_span,true)
321
354
  _code(property.declaration_span)
355
+ if property.initializer!=null:
356
+ _writer.append("preload("+_resource(Data)+").value(",property.initializer.span)
357
+ _parts(property.initializer.parts)
358
+ _writer.append(", "+property.data_type+", null, "+_string("%s:%d:%d"%[_file.name,property.name_span.start.line,property.name_span.start.column])+")",property.initializer.span)
322
359
  _writer.append(":",property.name_span)
323
360
  if property.comment_span != null:
324
361
  _writer.append(" ")
@@ -327,11 +364,19 @@ func _bindable(property: Model.Bindable) -> void:
327
364
  # Use the native property backing slot: accesses inside its own setter are
328
365
  # direct, and declaration initialization does not call the setter.
329
366
  _writer.append(indent.repeat(2)+"if is_same("+property.name+", "+incoming+"): return\n",property.name_span)
367
+ if _module.data_shape:
368
+ _writer.append(indent.repeat(2)+"if not preload("+_resource(Data)+").can_attach(self, "+incoming+"): push_error(\"Cyclic Gogo data assignment\"); return\n",property.name_span)
330
369
  _writer.append(indent.repeat(2)+"var "+previous+": ",property.name_span)
331
370
  _code(property.type_span)
332
371
  _writer.append(" = "+property.name+"\n",property.name_span)
333
372
  _writer.append(indent.repeat(2)+property.name+" = "+incoming+"\n",property.name_span)
334
- _writer.append(indent.repeat(2)+property.signal_name+".emit("+previous+", "+incoming+")\n",property.name_span)
373
+ var emission_indent := indent.repeat(2)
374
+ if _module.data_shape:
375
+ _writer.append(emission_indent+"if not preload("+_resource(Data)+").initializing(self):\n",property.name_span)
376
+ emission_indent += indent
377
+ _writer.append(emission_indent+"preload("+_resource(Data)+").refresh(self)\n",property.name_span)
378
+ _writer.append(emission_indent+property.signal_name+".emit("+previous+", "+incoming+")\n",property.name_span)
379
+ if _module.data_shape: _writer.append(emission_indent+"preload("+_resource(Data)+").notify(self)\n",property.name_span)
335
380
  _writer.append(indent+"get:\n"+indent.repeat(2)+"preload("+_resource(State)+").observe(self, &"+_string(property.signal_name)+")\n"+indent.repeat(2)+"return "+property.name+"\n",property.name_span)
336
381
 
337
382
  func _binding_argument(argument: Argument) -> void:
@@ -10,6 +10,7 @@ const Composition = preload("composition.gd")
10
10
  const Layouts = preload("layouts.gd")
11
11
  const RenderCalls = preload("render_calls.gd")
12
12
  const ImportAliases = preload("import_aliases.gd")
13
+ const Data = preload("data.gd")
13
14
 
14
15
  static func analyze(text: String, source_name: String = "<source>", output_path: String = "", project_sources = null) -> Model.Result:
15
16
  var file := Source.new(text, source_name, output_path, project_sources)
@@ -22,6 +23,7 @@ static func analyze(text: String, source_name: String = "<source>", output_path:
22
23
  if module != null and file.diagnostics.is_empty(): Validator.new(file).validate(module)
23
24
  if module != null and file.diagnostics.is_empty(): ImportAliases.new(file).apply(module)
24
25
  if module != null and file.diagnostics.is_empty(): RenderCalls.new(file).apply(module)
26
+ if module != null and file.diagnostics.is_empty(): Data.new(file).apply(module)
25
27
  result.tokens = parser.lexer.tokens
26
28
  result.diagnostics = file.diagnostics
27
29
  result.module = module if result.diagnostics.is_empty() else null
@@ -42,6 +42,8 @@ class Bindable extends SyntaxNode:
42
42
  var annotations_span: Span # Native property annotations, never attached to generated signal.
43
43
  var declaration_span: Span
44
44
  var comment_span: Span
45
+ var data_type: String = ""
46
+ var initializer: GdExpression
45
47
  func _init() -> void:
46
48
  kind = "bindable-property"
47
49
 
@@ -50,6 +52,15 @@ class GdExpression extends SyntaxNode:
50
52
  func _init() -> void:
51
53
  kind = "gdscript-expression"
52
54
 
55
+ class DataWrite extends SyntaxNode:
56
+ var prefix: Array[SyntaxNode] = []
57
+ var expression: Array[SyntaxNode] = []
58
+ var owner: Array[SyntaxNode] = []
59
+ var field: String = ""
60
+ var descriptor: String = ""
61
+ var previous: String = "null"
62
+ func _init() -> void: kind = "data-write"
63
+
53
64
  class Literal extends SyntaxNode:
54
65
  var value: Variant
55
66
  var type_name: String
@@ -111,6 +122,11 @@ class RenderCall extends SyntaxNode:
111
122
  func _init() -> void: kind = "render-call"
112
123
 
113
124
  class Module extends RefCounted:
125
+ var data_shape := false
126
+ var data_inherited := false
127
+ var data_notification := false
128
+ var data_types: Dictionary = {}
129
+ var data_type_edits: Array = []
114
130
  var render_functions: Array = []
115
131
  var ordinary_functions: Array = []
116
132
  var presets: Array = []
@@ -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.35"
6
+ version="0.1.0-beta.36"
7
7
  script="plugin.gd"
@@ -126,9 +126,15 @@ func call_at(site: String, callable: Callable, arguments: Array, _native_proof:
126
126
  # boundary. CORE02 can supply real upward change signals without revisions.
127
127
  for value in arguments:
128
128
  if typeof(value)!=TYPE_OBJECT or not is_instance_valid(value): continue
129
+ var data = preload("../data/state.tres")
130
+ var data_event: StringName = data.event(value)
131
+ if data_event!=&"":
132
+ opaque += 1
133
+ data.refresh(value)
134
+ opaque -= 1
129
135
  for signal_info in value.get_signal_list():
130
136
  var event: StringName = signal_info.name
131
- if event in [&"changed",&"tree_exiting"] or str(event).ends_with("_changed"):
137
+ if event==data_event or data_event==&"" and (event in [&"changed",&"tree_exiting"] or str(event).ends_with("_changed")):
132
138
  argument_reads[str(value.get_instance_id())+":"+str(event)] = [weakref(value),event]
133
139
  owner.watch(value,event,entry)
134
140
  var frame := {"entry":entry,"ordinals":{},"used":{}}
@@ -195,6 +201,7 @@ func in_slot(site: String, key, body: Callable):
195
201
  return result
196
202
 
197
203
  func method_at(site: String, receiver, method: StringName, arguments: Array, native_call: Callable, _native_proof: Callable = Callable(), reactive_lambda: bool = false):
204
+ if preload("../data/state.tres").is_collection(receiver): return receiver.callv(method,arguments)
198
205
  if receiver is Callable and method in [&"call",&"callv"]:
199
206
  return call_at(site,receiver,arguments[0] if method==&"callv" else arguments,Callable(),reactive_lambda)
200
207
  if typeof(receiver)==TYPE_OBJECT:
@@ -0,0 +1,111 @@
1
+ @tool
2
+ extends RefCounted
3
+ ## Optional ordered observable data. Native Arrays remain ordinary values.
4
+ signal changed
5
+ signal structure_changed
6
+ const Data = preload("state.tres")
7
+ var _values: Array = []
8
+ var element_type: Variant
9
+ var _batch := 0
10
+ var _pending := false
11
+
12
+ func _init(type: Variant = null, values: Array = []) -> void:
13
+ element_type = type
14
+ reset(values)
15
+ func _notification(what: int) -> void:
16
+ if what==NOTIFICATION_PREDELETE: Data.prune()
17
+
18
+ func size() -> int:
19
+ _observe()
20
+ return _values.size()
21
+ func is_empty() -> bool:
22
+ return size()==0
23
+ func at(index: int):
24
+ _observe()
25
+ return _values[index]
26
+ func to_array() -> Array:
27
+ _observe()
28
+ return _values.duplicate()
29
+ func map(callback: Callable) -> Array:
30
+ _observe()
31
+ var output: Array = []
32
+ var manager = preload("../composition/state.tres")
33
+ for item in _values:
34
+ # Inline callbacks retain compiler-owned lexical call sites; named Gogo
35
+ # render functions need the same invocation boundary as an authored call.
36
+ output.append(callback.call(item) if callback.is_custom() else manager.call_at("$collection-map:"+str(get_instance_id()),callback,[item]))
37
+ return output
38
+ func _iter_init(iterator: Array) -> bool:
39
+ _observe()
40
+ iterator[0] = 0
41
+ return not _values.is_empty()
42
+ func _iter_next(iterator: Array) -> bool:
43
+ iterator[0] += 1
44
+ return iterator[0]<_values.size()
45
+ func _iter_get(index):
46
+ return _values[index[0] if index is Array else index]
47
+ func append(value) -> bool:
48
+ return insert(_values.size(),value)
49
+ func insert(index: int, value) -> bool:
50
+ if index<0 or index>_values.size(): return _reject("insert index out of range")
51
+ var converted: Dictionary = Data.hydrate(value,element_type,"ArrayCollection[%d]" % index)
52
+ if not converted.ok: return _reject(converted.error)
53
+ if not Data.can_attach(self,converted.value): return _reject("cyclic collection membership")
54
+ _values.insert(index,converted.value)
55
+ _mutated()
56
+ return true
57
+ func remove_at(index: int) -> bool:
58
+ if index<0 or index>=_values.size(): return _reject("remove index out of range")
59
+ _values.remove_at(index)
60
+ _mutated()
61
+ return true
62
+ func replace(index: int, value) -> bool:
63
+ if index<0 or index>=_values.size(): return _reject("replace index out of range")
64
+ var converted: Dictionary = Data.hydrate(value,element_type,"ArrayCollection[%d]" % index)
65
+ if not converted.ok: return _reject(converted.error)
66
+ if not Data.can_attach(self,converted.value): return _reject("cyclic collection membership")
67
+ if is_same(_values[index],converted.value): return true
68
+ _values[index] = converted.value
69
+ _mutated()
70
+ return true
71
+ func move(from: int, to: int) -> bool:
72
+ if from<0 or from>=_values.size() or to<0 or to>=_values.size(): return _reject("move index out of range")
73
+ if from==to: return true
74
+ var value = _values.pop_at(from)
75
+ _values.insert(to,value)
76
+ _mutated()
77
+ return true
78
+ func reset(values: Array) -> bool:
79
+ var next: Array = []
80
+ for index in range(values.size()):
81
+ var converted: Dictionary = Data.hydrate(values[index],element_type,"ArrayCollection[%d]" % index)
82
+ if not converted.ok: return _reject(converted.error)
83
+ if not Data.can_attach(self,converted.value): return _reject("cyclic collection membership")
84
+ next.append(converted.value)
85
+ if next==_values: return true
86
+ _values = next
87
+ _mutated()
88
+ return true
89
+ func begin_update() -> void:
90
+ _batch += 1
91
+ func end_update() -> void:
92
+ if _batch==0:
93
+ _reject("end_update without begin_update")
94
+ return
95
+ _batch -= 1
96
+ if _batch==0 and _pending: _publish()
97
+ func _mutated() -> void:
98
+ Data.refresh(self)
99
+ _pending = true
100
+ if _batch==0: _publish()
101
+ func _publish() -> void:
102
+ _pending = false
103
+ structure_changed.emit()
104
+ Data.notify(self)
105
+ func _observe() -> void:
106
+ preload("../composition/state.tres").observe(self,&"structure_changed")
107
+ func _reject(message: String) -> bool:
108
+ push_error("ArrayCollection: "+message)
109
+ return false
110
+ func to_data():
111
+ return Data.to_data(self)
@@ -0,0 +1 @@
1
+ uid://bk8eqsjn6o4ld
@@ -0,0 +1,210 @@
1
+ @tool
2
+ extends Resource
3
+ ## Weak, external observation graph. No user-object metadata or second scheduler.
4
+ var records: Dictionary = {}
5
+ var _building: Dictionary = {}
6
+ var _emitting := false
7
+ var _visited: Dictionary = {}
8
+ var _hydrating: Dictionary = {}
9
+ func initializing(value: Object) -> bool:
10
+ return _hydrating.has(value.get_instance_id())
11
+ class Edge extends RefCounted:
12
+ var parent: WeakRef
13
+ var manager: WeakRef
14
+ func changed() -> void:
15
+ var source = parent.get_ref()
16
+ var state = manager.get_ref()
17
+ if source!=null and state!=null: state.notify(source)
18
+
19
+ func fields(value: Object) -> Dictionary:
20
+ var output := {}
21
+ var script = value.get_script()
22
+ while script is Script:
23
+ for key in script.get_script_constant_map():
24
+ if str(key).begins_with("_GOGO_BINDABLE_PROPERTIES_"):
25
+ output.merge(script.get_script_constant_map()[key],false)
26
+ script = script.get_base_script()
27
+ return output
28
+ func is_collection(value) -> bool:
29
+ return typeof(value)==TYPE_OBJECT and is_instance_valid(value) and value.get_script()==load(get_script().resource_path.get_base_dir().path_join("array_collection.gd"))
30
+ func event(value: Object) -> StringName:
31
+ return &"changed" if is_collection(value) else &"_gogo_data_changed" if value.has_signal(&"_gogo_data_changed") else &""
32
+ func children(value: Object) -> Array:
33
+ if is_collection(value): return value._values.duplicate()
34
+ var output: Array = []
35
+ for name in fields(value): output.append(value.get(name))
36
+ return output
37
+ func refresh(value: Object) -> void:
38
+ if event(value)==&"": return
39
+ var id := value.get_instance_id()
40
+ if _building.has(id): return
41
+ _building[id] = true
42
+ prune()
43
+ var record: Dictionary = records.get(id,{"source":weakref(value),"edges":{}})
44
+ var next := {}
45
+ for child in children(value):
46
+ if typeof(child)!=TYPE_OBJECT or not is_instance_valid(child) or event(child)==&"": continue
47
+ var child_id: int = child.get_instance_id()
48
+ if next.has(child_id): continue # Duplicate membership has one subscription.
49
+ refresh(child)
50
+ var child_event := event(child)
51
+ if record.edges.has(child_id):
52
+ next[child_id] = record.edges[child_id]
53
+ continue
54
+ var edge := Edge.new()
55
+ edge.parent = weakref(value)
56
+ edge.manager = weakref(self)
57
+ var callback := Callable(edge,"changed")
58
+ next[child_id] = [weakref(child),child_event,callback,edge]
59
+ if not child.is_connected(child_event,callback): child.connect(child_event,callback)
60
+ for child_id in record.edges:
61
+ if not next.has(child_id): _disconnect(record.edges[child_id])
62
+ record.edges = next
63
+ records[id] = record
64
+ _building.erase(id)
65
+ func prune() -> void:
66
+ for id in records.keys():
67
+ if records[id].source.get_ref()!=null: continue
68
+ for edge in records[id].edges.values(): _disconnect(edge)
69
+ records.erase(id)
70
+ func _disconnect(edge: Array) -> void:
71
+ var source = edge[0].get_ref()
72
+ if source!=null and source.is_connected(edge[1],edge[2]): source.disconnect(edge[1],edge[2])
73
+ func notify(value: Object) -> void:
74
+ var outer := not _emitting
75
+ if outer: _emitting = true; _visited.clear()
76
+ var id := value.get_instance_id()
77
+ if not _visited.has(id):
78
+ _visited[id] = true
79
+ value.emit_signal(event(value))
80
+ if outer: _emitting = false; _visited.clear()
81
+ func can_attach(owner: Object, value, seen: Dictionary = {}) -> bool:
82
+ if typeof(value)!=TYPE_OBJECT or not is_instance_valid(value): return true
83
+ if value==owner: return false
84
+ var id: int = value.get_instance_id()
85
+ if seen.has(id): return true
86
+ seen[id] = true
87
+ if event(value)!=&"":
88
+ for child in children(value):
89
+ if not can_attach(owner,child,seen): return false
90
+ return true
91
+ func hydrate(value, type, path: String = "data", ancestors: Array = []) -> Dictionary:
92
+ if type==null: return _plain(value,path,ancestors)
93
+ if type is Script:
94
+ var shape := false
95
+ for name in type.get_script_constant_map():
96
+ if str(name).begins_with("_GOGO_DATA_SHAPE_"): shape = true
97
+ if not shape or not ClassDB.is_parent_class(type.get_instance_base_type(),"RefCounted"): return _error(path,"type is not a Gogo plain-data shape")
98
+ if value==null: return {"ok":true,"value":null}
99
+ if typeof(value)==TYPE_OBJECT and is_instance_valid(value) and is_instance_of(value,type): return {"ok":true,"value":value}
100
+ if not value is Dictionary: return _error(path,"expected typed data Dictionary or model")
101
+ if _contains(ancestors,value): return _error(path,"cyclic data")
102
+ var model = type.new()
103
+ if event(model)==&"": return _error(path,"type is not a Gogo data shape")
104
+ var properties := fields(model)
105
+ var next := {}
106
+ var branch := ancestors+[value]
107
+ for key in value:
108
+ if not key is String or not properties.has(key): return _error(path,"unknown field "+str(key))
109
+ var target = _field_type(model,key,properties[key])
110
+ var result := hydrate(value[key],target,path+"."+key,branch)
111
+ if not result.ok: return result
112
+ next[key] = result.value
113
+ # Only publish the completely validated detached model.
114
+ _hydrating[model.get_instance_id()] = true
115
+ for key in next: model.set(key,next[key])
116
+ _hydrating.erase(model.get_instance_id())
117
+ refresh(model)
118
+ return {"ok":true,"value":model}
119
+ if type is Array and type.size()==1:
120
+ if value==null: return {"ok":true,"value":null}
121
+ if is_collection(value) and value.element_type==type[0]: return {"ok":true,"value":value}
122
+ if not value is Array: return _error(path,"expected collection Array")
123
+ if _contains(ancestors,value): return _error(path,"cyclic data")
124
+ var next: Array = []
125
+ for index in range(value.size()):
126
+ var result := hydrate(value[index],type[0],path+"[%d]"%index,ancestors+[value])
127
+ if not result.ok: return result
128
+ next.append(result.value)
129
+ return {"ok":true,"value":load(get_script().resource_path.get_base_dir().path_join("array_collection.gd")).new(type[0],next)}
130
+ if type is Dictionary and type.has("array"):
131
+ if not value is Array: return _error(path,"expected typed Array")
132
+ if _contains(ancestors,value): return _error(path,"cyclic data")
133
+ var next: Array = []
134
+ for index in range(value.size()):
135
+ var result := hydrate(value[index],type.array,path+"[%d]"%index,ancestors+[value])
136
+ if not result.ok: return result
137
+ next.append(result.value)
138
+ return {"ok":true,"value":Array(next,TYPE_OBJECT if type.array is Script else int(type.array),&"",type.array if type.array is Script else null)}
139
+ if int(type)==TYPE_FLOAT and typeof(value)==TYPE_INT: value = float(value)
140
+ if int(type)==TYPE_INT and typeof(value)==TYPE_FLOAT and is_finite(value) and value==floor(value): value = int(value)
141
+ if typeof(value)!=int(type): return _error(path,"incompatible value type "+str(typeof(value)))
142
+ return _plain(value,path,ancestors)
143
+ func _declared_type(model: Object, name: String):
144
+ var script = model.get_script()
145
+ while script is Script:
146
+ for key in script.get_script_constant_map():
147
+ if str(key).begins_with("_GOGO_DATA_TYPES_") and script.get_script_constant_map()[key].has(name): return script.get_script_constant_map()[key][name]
148
+ script = script.get_base_script()
149
+ return null
150
+ func _field_type(model: Object, name: String, _declaration: String):
151
+ var declared = _declared_type(model,name)
152
+ if declared!=null: return declared
153
+ for property in model.get_property_list():
154
+ if property.name==name: return property.type
155
+ return TYPE_NIL
156
+ func to_data(value):
157
+ var result := _encode(value,"data",[])
158
+ if not result.ok: push_error(result.error); return null
159
+ return result.value
160
+ func _encode(value, path: String, ancestors: Array) -> Dictionary:
161
+ if typeof(value)==TYPE_OBJECT:
162
+ if not is_instance_valid(value): return {"ok":true,"value":null}
163
+ if _contains(ancestors,value): return _error(path,"cyclic model")
164
+ if is_collection(value): return _encode(value._values,path,ancestors+[value])
165
+ if event(value)==&"": return _error(path,"unsupported native Object")
166
+ var output := {}
167
+ for name in fields(value):
168
+ var result := _encode(value.get(name),path+"."+name,ancestors+[value])
169
+ if not result.ok: return result
170
+ output[name] = result.value
171
+ return {"ok":true,"value":output}
172
+ return _plain(value,path,ancestors,true)
173
+ func _plain(value, path: String, ancestors: Array, encode: bool = false) -> Dictionary:
174
+ if value is Array or value is Dictionary:
175
+ if _contains(ancestors,value): return _error(path,"cyclic plain data")
176
+ var output = [] if value is Array else {}
177
+ for key in range(value.size()) if value is Array else value.keys():
178
+ if value is Dictionary and not key is String: return _error(path,"Dictionary keys must be Strings")
179
+ var result := _encode(value[key],path+"."+str(key),ancestors+[value]) if encode else _plain(value[key],path+"."+str(key),ancestors+[value])
180
+ if not result.ok: return result
181
+ if output is Array: output.append(result.value)
182
+ else: output[key] = result.value
183
+ return {"ok":true,"value":output}
184
+ if typeof(value) not in [TYPE_NIL,TYPE_BOOL,TYPE_INT,TYPE_FLOAT,TYPE_STRING]: return _error(path,"unsupported plain data value")
185
+ if typeof(value)==TYPE_FLOAT and not is_finite(value): return _error(path,"non-finite plain data number")
186
+ return {"ok":true,"value":value}
187
+ func _contains(values: Array, value) -> bool:
188
+ for ancestor in values:
189
+ if is_same(ancestor,value): return true
190
+ return false
191
+ func _error(path: String, message: String) -> Dictionary:
192
+ return {"ok":false,"error":path+": "+message}
193
+
194
+ func value(incoming, type, previous = null, path: String = "data"):
195
+ var result := hydrate(incoming,type,path)
196
+ if not result.ok:
197
+ push_error(result.error)
198
+ return previous
199
+ return result.value
200
+ func iterate(value):
201
+ return value
202
+ func assign(owner: Object, field: String, incoming, path: String = "data", _native_proof: Callable = Callable()) -> void:
203
+ var shape := fields(owner)
204
+ if not shape.has(field) and _declared_type(owner,field)==null:
205
+ owner.set(field,incoming)
206
+ return
207
+ var result := hydrate(incoming,_field_type(owner,field,shape.get(field,"")),path+"."+field)
208
+ if not result.ok: push_error(result.error); return
209
+ if not can_attach(owner,result.value): push_error(path+": cyclic data assignment"); return
210
+ owner.set(field,result.value)
@@ -0,0 +1 @@
1
+ uid://b035f5a1nc84f
@@ -0,0 +1,6 @@
1
+ [gd_resource type="Resource" load_steps=2 format=3]
2
+
3
+ [ext_resource type="Script" path="state.gd" id="1"]
4
+
5
+ [resource]
6
+ script = ExtResource("1")
package/package.json CHANGED
@@ -29,5 +29,5 @@
29
29
  "tag": "beta",
30
30
  "registry": "https://registry.npmjs.org/"
31
31
  },
32
- "version": "0.1.0-beta.35"
32
+ "version": "0.1.0-beta.36"
33
33
  }