-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
generate.cr
965 lines (825 loc) · 26.9 KB
/
generate.cr
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
require "json"
require "./tools/diff_util"
WITH_DOCS = ARGV.delete("--with-docs")
enum Context
Lib
Ext
Obj
end
macro assert(expr)
({{expr}}) || raise "Assertion failed: " + {{expr.stringify}}
end
macro def_map_from_json(field, parent_field = nil)
getter name : String
getter {{field}}
def initialize(@name : String, @{{field}})
{% if parent_field %}self.{{field.var}}.each &.{{parent_field}} = self{% end %}
end
def self.new(pull : JSON::PullParser)
self.new(pull.string_value, {{field.type}}.new(pull))
end
end
macro with_location(url = true, &block)
{% if !block %}
setter location : String?
{% end %}
def location? : Location?
{% if block %}
{{yield}}
{% else %}
Location.new(@location)
{% end %}
end
def location : Location
assert self.location?
end
def comment
return nil if !WITH_DOCS
return nil if self.location?.try(&.file) != "imgui.h"
first_comment = IMGUI_H[self.location.line - 1].partition("// ").last
unless first_comment.strip.empty?
first_comment.split(" // ").each do |s|
yield " # " + s.strip unless s.strip.empty?
end
{% if url %}
yield " #"
{% end %}
end
{% if url %}
yield " # [#{self.cpp_name}](#{location.url})"
{% end %}
end
end
class CType
NativeLib = {
"int" => "LibC::Int",
"unsigned int" => "LibC::UInt",
"short" => "LibC::Short",
"unsigned short" => "LibC::UShort",
"char" => "LibC::Char",
"unsigned char" => "LibC::UChar",
"signed char" => "LibC::SChar",
"size_t" => "LibC::SizeT",
"float" => "LibC::Float",
"double" => "LibC::Double",
"void" => "Void",
"bool" => "Bool",
"FILE" => "Void",
}
NativeCr = {
"int" => "Int32",
"unsigned int" => "UInt32",
"short" => "Int16",
"unsigned short" => "UInt16",
"float" => "Float32",
"double" => "Float64",
}
def self.native?(type : String, ctx : Context) : String?
if type =~ /^Im(S|(U))(\d+)$/
"#{$2?}Int#{$3}"
elsif ctx.lib?
NativeLib[type]?
else
NativeCr[type]? || NativeLib[type]?
end
end
getter c_name : String
getter? const : Bool
def initialize(c_name : String)
@c_name = c_name.gsub(/\bconst | const\b/, "")
@const = (@c_name != c_name)
@c_name = @c_name.lchop("struct ")
end
def self.new(name : String) : self
CFunctionType.new(name) rescue previous_def
end
def self.new(pull : JSON::PullParser)
self.new(String.new(pull))
end
def name(ctx : Context = Context::Lib) : String
self.base_name(ctx)
end
def base_type : CType
base_type = CType.new(self.c_name[/[\w ]+/]? || self.c_name)
end
def base_name(ctx : Context) : String
if ctx.obj? && self.const? && self.c_name == "char*"
return "String"
end
name = self.c_name.gsub("[]", "*")
name = name.gsub(/\[\d+\]/, "*") unless ctx.lib?
name = name.sub(/[\w ]+/) do |s|
CType.native?(s, ctx) || s
end
base_type = self.base_type
if ctx.obj? && base_type.class? && (t = name.rchop?("*"))
return t
end
if (t = base_type.struct? || base_type.enum?)
in_lib = (base_type.class? || (t.internal? && base_type.struct?) || name.starts_with?("ImVector") && !ctx.obj?)
if ctx.lib?
name = "ImGui::#{name}" if !in_lib
else
name = "LibImGui::#{name}" if in_lib
end
end
name
end
def enum? : CEnum?
if self.c_name.starts_with?("Im")
AllEnums.values.find { |e| e.name == self.c_name }
end
end
def struct? : CStruct?
AllStructs[self.c_name.sub("[]", "*")]?
end
def class? : Bool
!!(struct?.try &.class?)
end
end
class CTemplateType < CType
getter template : CType
def initialize(c_name, @template)
super(c_name)
end
def name(ctx : Context) : String
name = self.base_name(ctx)
index = assert (name + " ").rindex(/\b/)
insert = ctx.obj? ? "(#{self.template.name(ctx)})" : "Internal"
name.insert(index, insert)
end
end
class CFunctionType < CType
def initialize(c_name)
super
assert c_name =~ /^(.+)?\(\*\)\((.*)\)/
type, args = $1, $2
@type = CType.new(type)
@args = args.split(",").map do |arg|
type, _, name = arg.gsub(" *", "* ").rpartition(" ")
if type == ""
type = name
end
CArg.new(CType.new(type), name)
end
end
def name(ctx : Context = Context::Lib) : String
args = self.args.map { |arg| arg.type.name(ctx) }.select { |t| t != "..." }
"(#{args.join(", ")}) -> #{self.type.name(ctx)}"
end
getter type : CType
getter args : Array(CArg)
end
class CArg
include JSON::Serializable
getter name : String
def name : String
name = @name
name += "_" if name == "in"
name
end
getter type : CType
def type : CType
if @type.c_name =~ /^(ImVector)_(\w+)(.*)/
t = CType.new($2)
assert !t.class?
CTemplateType.new("#{$1}#{$3}", t)
else
@type
end
end
getter reftoptr : Bool = true
getter ret : String?
getter signature : String?
def initialize(@type, @name)
end
end
class COverload
include JSON::Serializable
# getter args : String
@[JSON::Field(key: "argsT")]
getter args : Array(CArg)
@[JSON::Field(key: "argsoriginal")]
getter args_orig : String?
getter call_args : String
@cimguiname : String
getter defaults : Hash(String, String)
getter funcname : String?
def funcname : String
@funcname || begin
assert self.c_name.ends_with?("_destroy")
"destroy"
end
end
property location : String?
with_location do
Location.new(@location) || parent.overloads.find(&.@location).try(&.location?)
end
@[JSON::Field(key: "ov_cimguiname")]
getter c_name : String
def c_name : String
if @c_name =~ /^ig[A-Z]/
@c_name.lchop("ig")
else
@c_name
end
end
def name(ctx : Context) : String
if ctx.obj?
if self.destructor?
"finalize"
elsif self.constructor?
"self.new"
else
self.funcname.gsub(/(?<=[A-Z])to(?=[A-Z])/, "To").underscore
end
else
self.c_name
end
end
def cpp_name : String
"#{"ImGui::" if !@stname.presence}#{"~" if self.destructor?}" + [@stname.presence, @funcname].compact.join("::") + "()"
end
getter ret : CType?
def ret : CType?
if (t = @ret)
t if !t.c_name.in?("void", "")
else
assert self.parent.name == "#{self.funcname}_#{self.funcname}"
CType.new("#{self.funcname}*")
end
end
getter signature : String
@stname : String?
def struct? : CStruct?
if (stname = @stname.presence)
AllStructs[stname]?
end
end
@[JSON::Field(key: "nonUDT")]
getter non_udt : Int32?
@[JSON::Field(key: "retorig")]
getter ret_orig : String?
getter? constructor : Bool = false
getter? destructor : Bool = false
getter isvararg : String?
getter? manual : Bool = false
getter? templated : Bool = false
getter retref : String?
getter namespace : String?
property! parent : CFunction
def parent=(parent : CFunction)
assert parent.name == @cimguiname
@parent = parent
end
def internal? : Bool
!!self.location?.try(&.internal?) || (self.funcname || "").starts_with?("_")
end
def input_output_arg? : Int32?
idx = self.args.index do |arg|
arg.type.name(Context::Obj).ends_with?("*") && (arg.name.split("_")[0].in?("p", "v") || arg.name.in?("current_item", "col", "flags"))
end
if idx
idx -= self.args.count { |arg| arg.type.c_name == "ImGuiDataType" }
end
idx
end
def render(ctx, inside_class = false, &block : String ->)
return if self.templated?
return if self.destructor?
return if self.args.any? { |arg| arg.type.c_name == "va_list" }
if ctx.lib?
args = self.args.map do |arg|
next "..." if arg.type.c_name == "..."
"#{arg.name} : #{arg.type.name(ctx).gsub(/\[\d+\]/, "*")}"
end
ret = self.ret.try &.name(ctx)
yield %(fun #{self.c_name} = #{@c_name}(#{args.join(", ")})#{" : #{ret}" if ret})
end
return if self.internal?
if ctx.obj?
return if self.struct? && !inside_class
args = [] of String
call_args = [] of String
macro_args = [] of String
rets = [self.ret].compact
outp = ["result"] * rets.size
conv = {} of String => String
outputter = nil
as_datatype = self.args.index { |arg| arg.type.c_name == "ImGuiDataType" }
if as_datatype
yield %( {% for k, t in {S8: Int8, U8: UInt8, S16: Int16, U16: UInt16, S32: Int32, U32: UInt32, S64: Int64, U64: UInt64, Float: Float32, Double: Float64} %})
end
self.args.each_with_index do |arg, arg_i|
if arg.type.c_name == "..."
args << %(*args)
call_args << %(*args._promote_va_args)
next
end
if arg.name == "pOut" || arg.name.split("_").first == "out"
outp << %(#{arg.name.underscore})
call_args << %(out #{arg.name.underscore})
rets << CType.new(arg.type.name.rchop("*"))
next
end
default = self.defaults[arg.name]?.try do |default|
default
.gsub(/\b(?<![%.])([0-9.]+)f\b(?!")/, "\\1")
.gsub(/\b(ImVec\d)\(/, "\\1.new(")
.gsub("(ImU32)", "UInt32.new")
.gsub(/\bNULL\b/, "nil")
.gsub(/\bfloat\b/, "Float32")
.gsub(/\bFLT_MAX\b/, "Float32::MAX")
.gsub(/\bFLT_MIN\b/, "Float32::MIN_POSITIVE")
end
typ = arg.type.name(ctx)
callarg = arg.name
if arg.name == "ptr_id" && typ == "Void*"
typ = "Reference | ClassType | Int | #{typ}"
callarg = "to_void_id(#{callarg})"
elsif arg.type.c_name =~ /^(float|int)\[(\d+)\]$/
t = typ.rchop("*")
n = $2.to_i
typ = "Indexable(#{t}) | #{typ}"
if $1 == "float"
typ = "ImVec2* | #{typ}" if n == 2
typ = "ImVec4* | #{typ}" if n == 4 || arg.name.rpartition("_").last == "col"
end
callarg = %(#{callarg}.is_a?(Indexable) ? (
#{callarg}.size == #{n} ? #{callarg}.to_unsafe : raise ArgumentError.new("Slice has wrong size \#{#{callarg}.size} (want #{n})")
) : #{callarg}.as(#{t}*))
elsif arg.name.rpartition("_").last == "end" && typ == "String"
assert (p_arg = self.args[arg_i - 1].name.rchop("_begin")) == arg.name.rpartition("_").first
args[-1] = "#{p_arg} : Bytes | String"
call_args[-1] = p_arg
call_args << "(#{p_arg}.to_unsafe + #{p_arg}.bytesize)"
next
elsif arg.name.rpartition("_").last == "size" && typ == "LibC::SizeT" && (prev_arg = self.args[arg_i - 1]?) && prev_arg.name == arg.name.rpartition("_").first && args[-1]?.try(&.ends_with?("Char*"))
typ = CType.new(assert prev_arg.type.name(Context::Ext).rchop?("*")).name(ctx)
args[-1] = "#{prev_arg.name} : Bytes"
call_args << "#{prev_arg.name}.size"
next
elsif arg.name.rpartition("_").last == "count" && typ == "Int32" && (prev_arg = self.args[arg_i - 1]?) && prev_arg.name == arg.name.rpartition("_").first && args[-1]?.try(&.ends_with?("*"))
typ = CType.new(assert prev_arg.type.name(Context::Ext).rchop?("*")).name(ctx)
args[-1] = "#{prev_arg.name} : Indexable(#{typ})"
call_args << "#{prev_arg.name}.size"
next
elsif arg.name == "current_item" && typ == "Int32*"
typ += " | Pointer"
callarg = "(typeof(#{callarg}.value.to_i32); #{callarg}.as(Int32*))"
elsif arg_i == as_datatype
call_args << "ImGuiDataType::{{k.id}}"
next
elsif as_datatype && arg_i > as_datatype && typ == "Void*" && arg.name.partition("_").first == "p"
typ = "{{t}}"
if arg_i - 1 == as_datatype || self.name(Context::Obj).ends_with?("n")
typ += "*"
else
callarg = "#{callarg} ? (#{callarg}_ = #{callarg}; pointerof(#{callarg}_)) : Pointer({{t}}).null"
end
# callarg += ".as(Void*)"
end
if default == "nil"
if (t = typ.rchop?("*"))
default = "Pointer(#{t}).null"
else
typ += "?" unless typ.ends_with?("?")
end
end
if arg.type.enum? && default =~ /^\d/
default = "#{typ}.new(#{default})"
end
if arg.type.enum? && default
default = default.gsub(/\B_\B/, "::")
end
args << "#{arg.name} : #{typ}#{" = #{default}" if default}" unless arg.name == "self"
call_args << "#{callarg}"
end
outp2 = outp.dup
outp2, rets = convert_returns!(outp2, rets)
ret_s = to_tuple(rets) || "Void"
any_outputter = self.parent.overloads.any?(&.input_output_arg?)
self.comment(&block)
def_name = self.name(ctx)
yield %( #{"pointer_wrapper " if any_outputter}def #{"self." if !inside_class}#{def_name}(#{args.join(", ")}) : #{ret_s})
call = %( LibImGui.#{self.name(Context::Lib)}(#{call_args.join(", ")}))
call = %( result = #{call}) if outp.first? == "result" && outp2 != ["result"]
yield call
yield (assert to_tuple(outp2)) unless outp2.empty? || outp2 == ["result"]
yield %( end)
yield %( {% end %}) if as_datatype
return if inside_class
always_pop_names = %w[begin begin_child begin_child_frame begin_disabled begin_group begin_tooltip push_allow_keyboard_focus push_button_repeat push_clip_rect push_clip_rect_full_screen push_font push_id push_item_width push_style_color push_style_var push_tab_stop push_texture_id push_text_wrap_pos tree_push]
cond_pop_names = %w[begin_combo begin_drag_drop_source begin_drag_drop_target begin_list_box begin_main_menu_bar begin_menu begin_menu_bar begin_popup begin_popup_context_item begin_popup_context_void begin_popup_context_window begin_popup_modal begin_tab_bar begin_tab_item begin_table tree_node tree_node_ex]
if (cond_pop = cond_pop_names.includes?(def_name)) || always_pop_names.includes?(def_name)
cond_call = !cond_pop && (ret_s == "Bool")
if def_name.starts_with?("tree_node")
new_name = def_name
pop_name = "tree_pop"
elsif def_name == "tree_push"
new_name = "with_tree"
pop_name = "tree_pop"
else
push, sep, common = def_name.partition('_')
new_name = ({"push" => "with", "begin" => ""}[push] + sep + common).lchop("_")
pop_name = {"push" => "pop", "begin" => "end"}[push] + sep + common
end
if def_name == "begin"
new_name = "window"
elsif def_name.starts_with?("begin_popup")
pop_name = "end_popup"
end
yield %( # Calls `#{def_name}`, #{"conditionally " if cond_pop || cond_call}yields to the block, then #{"conditionally " if cond_pop}calls `#{pop_name}`.)
yield %( #{"pointer_wrapper " if any_outputter}def self.#{new_name}(#{args.join(", ")}) : Nil)
yield %( #{cond_pop ? "return unless " : cond_call ? "yield if " : ""}self.#{def_name}(#{args.map(&.partition(' ').first).join(", ")}))
yield %( yield) if !cond_call
yield %( self.#{pop_name})
yield %( end)
end
end
end
end
def to_tuple(args : Array(String)) : String?
args.size > 1 ? "{" + args.join(", ") + "}" : args.join(", ").presence
end
def convert_returns!(outp : Array(String), rets : Array(CType), member = false) : {Array(String), Array(String)}
orig_rets = rets
rets = rets.map(&.name(Context::Obj))
outp.each_with_index do |o, i|
ret = orig_rets[i]
if ret.c_name =~ /\d\]$/
outp[i] = %(#{o}.to_slice)
rets[i] = "Slice(#{ret.name(Context::Obj).rchop("*")})"
elsif (t = ret.base_type.struct?) || ret.name(Context::Obj) == "String"
if t && t.class? && !t.internal?
outp[i] = %(#{ret.name(Context::Obj)}.new(#{o}))
if ret.const? || ret.name.in? %w[ImGuiTableSortSpecs*]
outp[i] = %(#{o} ? #{outp[i]} : nil)
rets[i] += "?"
end
else
rets[i] = ret.name(Context::Obj).rchop("*")
if member && ret.name.rchop?("*")
rets[i] += "?"
if ret.name(Context::Obj) == "String"
outp[i] = %((v = #{o}) ? String.new(v) : nil)
else
outp[i] = %((v = #{o}) ? v.value : nil)
end
elsif ret.name(Context::Obj) == "String"
outp[i] = %(String.new(#{o}))
else
outp[i] = o + ".value" if ret.name.rchop?("*")
end
end
end
end
{outp, rets}
end
class CFunction
def_map_from_json(overloads : Array(COverload), parent)
def render(ctx, inside_class = false, &block : String ->)
self.overloads.each &.render(ctx, inside_class, &block)
end
def location? : Location?
self.overloads.find(&.location?).try(&.location)
end
getter? struct : CStruct? do
result : CStruct? = nil
self.overloads.each do |overload|
result ||= overload.struct?
assert result == overload.struct?
end
result
end
end
AllFunctions = Hash(String, CFunction).from_json(
File.read("cimgui/generator/output/definitions.json")
)
class CStructMember
include JSON::Serializable
@[JSON::Field(key: "name")]
getter c_name : String
def c_name : String
@c_name.partition("[")[0]
end
def name(ctx : Context) : String
self.c_name.underscore.presence || "val"
end
@[JSON::Field(key: "type")]
getter c_type : String
def type : CType
c_type = self.c_type
c_type += "[#{self.size}]" if self.size
if (tpl = self.template_type)
type = assert c_type.rchop?("_" + tpl.gsub("*", "Ptr").gsub(" ", "_"))
CTemplateType.new(type, CType.new(tpl))
else
CType.new(c_type)
end
end
getter bitfield : String?
getter template_type : String?
getter size : Int32?
property! parent : CStruct
with_location(url: false) do
return nil if parent.location?.try(&.file) != "imgui.h"
regex = /^[^{\/]*\b#{self.c_name}(\[[^\[\]]+\]|\)\(.+?\))*( : \d+)?[;,]/
(parent.location.line + 1).step do |line|
if IMGUI_H[line - 1] =~ regex
return Location.new(parent.location.file, line)
end
end
nil
end
def initialize(@c_type, @c_name)
end
def internal? : Bool
self.c_name.starts_with?("_")
end
def render(ctx : Context, &block : String ->)
varname = self.name(ctx)
typ = self.type
if ctx.lib?
yield %(#{varname} : #{typ.name(ctx)})
return
end
return if self.internal? && !ctx.ext?
this = (self.parent.class? ? "@this.value." : "@")
typeinternal = typ.name(Context::Ext)
set_call = %(#{this}#{varname} = #{varname})
if {varname, typ.name(Context::Obj)}.in?({
{"cmd_lists", "ImDrawList*"},
{"config_data", "ImFontConfig"},
{"specs", "ImGuiTableColumnSortSpecs"},
})
t = typ.name(Context::Obj).rchop("*")
typename = "Slice(#{t})"
call = %(Slice.new(#{this}#{varname}_count.to_i) { |i| #{t}.new(#{this}#{varname} + i) })
set_call = %(#{this}#{varname}, #{this}#{varname}_count = #{varname}.to_unsafe, #{varname}.bytesize)
else
if typ.class?
typ = CType.new(typ.name + "*")
end
call, rets = convert_returns!(["#{this}#{varname}"], [typ], true)
call = call.first
typename = rets.first
end
if ctx.ext? && !self.parent.class?
yield %(#{self.internal? ? "@" : "property "}#{varname} : #{self.type.name(ctx)})
end
if ctx.obj?
if (self.type.is_a?(CTemplateType)) && ctx.obj?
self.comment(&block)
yield %(def #{varname} : #{typename})
yield %(t = #{this}#{varname})
yield %(pointerof(t).as(#{typename}*).value)
yield %(end)
yield %(def #{varname}=(#{varname} : #{typename}))
yield set_call += %(.as(#{typeinternal}*).value)
yield %(end)
elsif self.parent.class?
self.comment(&block)
yield %(def #{varname} : #{typename})
yield call
yield %(end)
yield %(def #{varname}=(#{varname} : #{typename}))
yield set_call
yield %(end)
end
end
end
end
class CStruct
def_map_from_json(members : Array(CStructMember), parent)
def render(ctx : Context, &block : String ->)
if self.internal?
if ctx.lib?
yield %(type #{self.name} = Void*)
elsif ctx.obj? && self.name.in?("ImGuiContext")
yield %(alias #{self.name} = LibImGui::#{self.name})
end
elsif ctx.obj?
self.comment(&block)
if self.class?
yield %(struct #{self.name})
yield %(include ClassType(LibImGui::#{self.name}))
else
yield %(struct #{self.name})
yield %(include StructType)
end
self.members.each &.render(ctx, &block)
self.functions.sort_by! { |x|
x.location? || Location.new(":0")
}.each &.render(ctx, true, &block)
yield %(end)
yield %(alias TopLevel::#{name} = ImGui::#{name}) if self.class?
elsif self.class? && ctx.lib?
yield %(struct #{self.name})
self.members.each do |member|
member.render(ctx, &block)
end
yield %(end)
elsif !self.class? && ctx.ext?
yield %()
yield %(@[Extern])
yield %(struct #{self.name})
self.members.each do |member|
member.render(ctx, &block)
end
args = self.members.map { |member| "@#{member.name(ctx)} : #{member.type.name(ctx)}" }
if !args.empty?
yield %(def initialize(#{args.join(", ")}))
yield %(end)
end
yield %(end)
yield %(alias TopLevel::#{name} = ImGui::#{name})
end
end
def cpp_name : String
"struct #{self.name}"
end
with_location
def internal? : Bool
!!self.location?.try(&.internal?) || self.name.in?("ImGuiStoragePair", "ImGuiTextRange", "ImGuiTextBuffer")
end
getter functions : Array(CFunction) do
AllFunctions.values.select { |d| d.struct?.try(&.name) == self.name }
end
def class? : Bool
!%w[ImVector ImVec2 ImVec4 ImColor ImDrawVert ImFontGlyph ImGuiTextRange ImGuiOnceUponAFrame ImGuiStorage ImGuiTextBuffer ImGuiListClipper ImFontGlyphRangesBuilder ImDrawChannel].includes?(self.name)
end
end
AllStructs = Hash(String, CStruct).from_json(
File.read("cimgui/generator/output/structs_and_enums.json"), "structs"
)
AllStructs["ImVector"] = CStruct.new("ImVector", [] of CStructMember).tap do |s|
s.location = "imgui:#{IMGUI_H.index("struct ImVector").not_nil! + 1}"
end
class CEnumMember
include JSON::Serializable
getter calc_value : Int32
@[JSON::Field(key: "name")]
getter c_name : String
def name : String
name = (assert(self.c_name.lchop?(self.parent.name) || self.c_name.lchop?("ImGui"))).lchop("_")
if name.to_i?
name = "Num#{name}"
end
if (chop = name.lchop?("_"))
name = "#{chop}_"
end
name
end
getter value : String
def value : String
val = @value
self.parent.members.each do |member|
val = val.sub(member.c_name, member.name)
end
val
end
property! parent : CEnum
with_location(url: false) do
return nil if parent.location?.try(&.file) != "imgui.h"
regex = /^[ \w,]*#{self.c_name}(,|$| *[=\/])/
(parent.location.line + 1).step do |line|
if IMGUI_H[line - 1] =~ regex
return Location.new(parent.location.file, line)
end
end
nil
end
end
class CEnum
def_map_from_json(members : Array(CEnumMember), parent)
def name : String
@name.rchop("_")
end
def cpp_name : String
"enum #{@name}"
end
def render(ctx : Context, &block : String ->)
return unless ctx.ext?
return if self.name.ends_with?("Private")
yield %()
yield "# :nodoc:" if self.internal?
self.comment(&block)
yield %(@[Flags]) if self.name.ends_with?("Flags")
yield %(enum #{name})
self.members.each do |member|
next if member.name == "All"
next if member.name == "COUNT" && self.name != "ImGuiKey"
next if member.name =~ /_[A-Z]{2,}$/
member.comment(&block)
yield %(#{member.name} = #{member.value})
end
yield %(end)
yield %(alias TopLevel::#{name} = ImGui::#{name}) unless self.internal?
end
with_location
def internal? : Bool
!!self.location?.try(&.internal?)
end
end
AllEnums = Hash(String, CEnum).from_json(
File.read("cimgui/generator/output/structs_and_enums.json"), "enums"
)
Hash(String, String).from_json(
File.read("cimgui/generator/output/structs_and_enums.json"), "locations"
).each do |type, location|
(AllEnums[type]? || AllStructs[type]).location = location
end
class CTypedef
def_map_from_json(type : CType)
def render(ctx : Context, &block : String ->)
return if CType.native?(self.name, ctx)
return unless self.name[0].ascii_uppercase?
return if AllEnums.has_key?(self.name + "_")
type_name = self.type.name(ctx)
return if type_name.includes?('<')
if self.name == self.type.c_name
return if AllStructs.has_key?(self.name)
yield %(alias #{self.name} = Void) if ctx.lib?
else
if ctx.lib?
return if self.name == "ImWchar"
yield %(alias #{self.name} = #{type_name})
elsif ctx.ext?
yield %(alias #{self.name} = LibImGui::#{self.name})
end
end
end
def location? : Nil
nil
end
end
AllTypedefs = Hash(String, String).from_json(
File.read("cimgui/generator/output/typedefs_dict.json")
).map { |k, v|
{k, CTypedef.new(k, CType.new(v.rchop(";")))}
}.to_h
struct Location
getter file : String
getter line : Int32
def initialize(@file, @line)
end
def <=>(other : Location)
return self.file <=> other.file if self.file != other.file
return self.line <=> other.line
end
def self.new(pair : String) : Location?
file, _, line = pair.partition(":")
self.new("#{file}.h", line.to_i)
end
def self.new(pair : Nil) : Nil
nil
end
def internal? : Bool
self.file != "imgui.h"
end
def url
github_file_url("cimgui/imgui", self.file, self.line)
end
end
IMGUI_H = File.read_lines("cimgui/imgui/imgui.h")
def render(ctx : Context, &block : String ->)
if ctx.lib?
yield %(require "./custom")
yield %(require "./types")
yield %()
yield %(@[Link("cimgui")])
yield %(lib LibImGui)
else
yield %(require "./lib") if ctx.obj?
yield %(module ImGui)
end
if ctx.ext?
IMGUI_H.each do |line|
if line =~ /^ *#define +IMGUI_((?:VERSION|PAYLOAD_TYPE)\w*) +([^\/]+)/
yield "#{$1} = #{$2}"
end
end
yield ""
end
items = AllEnums.values + AllTypedefs.values + AllStructs.values + AllFunctions.values
items.sort_by! { |x| {x.location? || Location.new(":0"), x.name} }
items.each do |it|
case it
in CEnum ; it.render(ctx, &block)
in CTypedef ; it.render(ctx, &block)
in CStruct ; it.render(ctx, &block)
in CFunction; it.render(ctx, &block)
end
end
yield %(end)
end
File.open("src/lib.cr", "w") do |f|
render(Context::Lib, &->f.puts(String))
end
File.open("src/types.cr", "w") do |f|
render(Context::Ext, &->f.puts(String))
end
File.open("src/obj.cr", "w") do |f|
render(Context::Obj, &->f.puts(String))
end