-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathgenerate.cr
1898 lines (1722 loc) · 61.4 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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2016 Oleh Prypin <oleh@pryp.in>
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgement in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
require "digest/sha1"
require "./tools/serialize_docs"
LIB_NAME = "SFMLExt"
PREFIX = "sfml_"
DEBUG = ARGV.delete("--debug")
SAVE_DOCS = ARGV.delete("--save-docs") ? Hash(String, Hash(String, Array(String))).new : nil
INCLUDE_DIR = ARGV[0]? || "/usr/include"
SFML_PATH = File.join(INCLUDE_DIR,
File.basename(INCLUDE_DIR) == "SFML.framework" ? "Headers" : "SFML"
)
MODULE_CLASSES = %w[NonCopyable GlResource Drawable RenderTarget AlResource]
STRUCTS = %w[IntRect FloatRect Vector2i Vector2u Vector2f Vector3f Time Transform IpAddress Music::TimeSpan]
enum Context
CHeader
CPPSource
Crystal
CrystalLib
def cr?
crystal? || crystal_lib?
end
end
enum Visibility
Private
Protected
Public
end
alias CTypeBase = CClass | CEnum | CNativeType
class CType
@@all = {} of String => CTypeBase
def self.all
@@all
end
def initialize(@type : CTypeBase, @reference = false, @pointer = 0, @const = false, @array = 1)
end
getter type : CTypeBase
getter? reference : Bool
getter pointer : Int32
getter? const : Bool
getter array : Int32
def void? : Bool
(type = self.type).is_a?(CNativeType) && type.full_name == "void" && pointer == 0
end
def full_name : String
r = type.full_name
r += " const" if const?
r += "*"*pointer
r += "&" if reference?
r
end
forward_missing_to @type
end
def register_type(type : CTypeBase, full_name : String = type.full_name)
CType.all[full_name] = type
CType.all["String"] = CNativeType.new("String")
end
STRUCTS.each do |name|
register_type CClass.new(name)
end
%w[VkInstance VkSurfaceKHR VulkanFunctionPointer].each do |name|
register_type CClass.new(name)
end
memory_buffer = CClass.new("MemoryBuffer")
memory_buffer << CFunction.new(name: "data", type: make_type("Uint8*", nil), parameters: [] of CParameter, parent: memory_buffer)
memory_buffer << CFunction.new(name: "size", type: make_type("std::size_t", nil), parameters: [] of CParameter, parent: memory_buffer)
memory_buffer << CFunction.new(name: "clear", type: nil, parameters: [] of CParameter, parent: memory_buffer)
register_type memory_buffer
def find_type(name : String, parent : CNamespace?) : CTypeBase
loop do
if parent
parents = [parent]
if parent.is_a?(CClass) && (inh = parent.inherited_class)
parents << inh
end
full_names = parents.map { |parent| "#{parent.full_name}::#{name}" }
else
full_names = [name]
end
CType.all.each do |name, type|
if full_names.includes? name
return type
end
end
if !parent
return CNativeType.new(name)
end
parent = parent.parent
end
end
macro remove_and_count(string, remove)
%count = 0
{{string.id}} = {{string.id}}.gsub({{remove}}) {
%count += 1
""
}
%count
end
def make_type(name : String, parent : CNamespace?) : CType
array = 1
name = name.sub /\[([0-9]+)\]$/ do
array = $1.to_i
""
end
info = {
reference: remove_and_count(name, "&") > 0,
pointer: remove_and_count(name, "*"),
const: remove_and_count(name, /\bconst\b/) > 0,
array: array,
}
name = name.strip
if name == "std::vector<sf::Uint8>"
name = "MemoryBuffer"
end
type = find_type(name, parent)
CType.new(type, **info)
end
def identifier_hash(string) : String
base = 62
size = 3
digest = Digest::SHA1.digest(string)
number = 0u64
(digest.size - sizeof(UInt64) ... digest.size).each do |i|
number <<= 8
number |= digest[i]
end
(number % (base**size)).to_s(base).rjust(3, '0')
end
abstract class CItem
def initialize(@name : String?, @visibility = Visibility::Public, @parent : CNamespace? = nil,
@docs : Array(String) = [] of String, @sfmodule : CModule? = nil)
end
getter parent : CNamespace?
getter docs : Array(String) = [] of String
getter visibility = Visibility::Public
def name(context : Context) : String?
@name
end
def full_name(context = Context::CPPSource) : String
result = (name(context) || "@")
if (parent = @parent)
sep = (context.crystal_lib? ? "_" : "::")
result = parent.full_name(context) + sep + result
end
result
end
def qualname : String
parts = [parent.try(&.qualname) || "SF", name(Context::Crystal)]
parts.compact.join("::")
end
def sfmodule : CModule
@sfmodule || parent.not_nil!.sfmodule
end
abstract def render(context : Context, out o : Output)
def render_docs(out o : Output, name : String)
in_code = false
in_annot = false
while @docs[-1]? == ""
@docs.pop
end
doc = String.build do |io|
prev_line = ""
in_list = false
@docs.each do |line|
if line == ""
in_list = false
end
if line == "\\code"
in_code = true
line = "```c++"
elsif line == "\\endcode"
in_code = false
line = "```"
end
unless in_code
if line.starts_with? "\\"
in_annot = true
elsif !line.starts_with? " "
in_annot = false
end
line = line.lstrip if in_annot
line = line.sub /^\\brief\b */, ""
line = line.sub /^\\li\b */ do
io << "\n" unless in_list
in_list = true
"* "
end
line = line.sub /^ \b/, " "
old_line = line
line = line.sub /^\\param\b +([^ ()]+) +/ { "* *#{CParameter.new($1, make_type("", nil)).name(Context::Crystal)}* - " }
line = line.sub /^\\(ingroup|relates)\b.*/, ""
line = line.sub /^\\return +/, "*Returns:* "
line = line.sub /^(\\warning\b|Warning:) +/, "WARNING: "
line = line.sub /^\\deprecated\b */, "DEPRECATED: "
if old_line != line && prev_line != "" && line.starts_with?("* ") != prev_line.starts_with?("* ")
io << "\n"
end
line = line.gsub /(@ref|\\a) +([^ (),.]+)/ { "*#{$2.underscore}*" }
line = line.gsub /\\(em|p) +([^ (),.]+)/ { "*#{$2}*" }
line = line.gsub /\\b +([^ (),.]+)/ { "**#{$1}**" }
line = line.sub /^\\overload\b/, ":ditto:"
line = line.gsub /\bsf(::[^ \.;,()]+)\b/ { "`SF#{$1}`" }
line = line.sub /(?<= )[a-z]\w+\b\(\)\B/ { "`#{$0}`" }
line = line.sub /^\\see\b *(.+)/ { "*See also:* " + $1.gsub(/(?<!`)\b[\w\.]+\b(?!`)/, "`\\0`") }
line = line.gsub /%([A-Z][a-zA-Z])/ { $1 }
line = line.gsub /<\/?b>/, "**"
line = line.gsub "\\n", "\n"
line = line.gsub '<', "<"
line = line.gsub '>', ">"
line = line.gsub /\b([a-z][a-z0-9]+[A-Z][a-zA-Z0-9]*)\b/ { CFunction.new($1, nil, [] of CParameter).name(Context::Crystal) }
end
io << "#{line.rstrip}\n" unless line == "" == prev_line
prev_line = line
end
end
if (saved_docs = SAVE_DOCS) && !{"", ":nodoc:"}.includes?(doc.strip)
module_docs = (saved_docs[sfmodule.name] ||= {} of String => Array(String))
(module_docs[name] ||= [] of String) << doc
end
if (docs = CModule.docs[name]?)
doc = docs.shift
if docs.empty?
CModule.docs.delete name
end
end
doc.lines.each do |line|
o<< "# #{line}"
end
end
end
abstract class CNamespace < CItem
include Enumerable(CItem)
getter items = [] of CItem
def each
items.each do |x|
yield x
end
end
def <<(item : CItem)
@items << item
end
end
class CClass < CNamespace
def initialize(name : String?, inherited = [] of String, *args, **kwargs)
super(name, *args, **kwargs)
@inherited_class = nil
@inherited_modules = [] of String
inherited.each do |cls|
if MODULE_CLASSES.includes? cls
@inherited_modules << cls
else
@inherited_class = inh = find_type(cls, parent).as CClass
end
end
end
getter inherited_class : CClass?
getter inherited_modules : Array(String)
def render(context : Context, out o : Output)
return unless @visibility.public?
return if @name.not_nil! =~ /<|^String$|^ThreadLocal|SoundFile|^Lock$|^Chunk$/
if abstract? && class?
buf = [] of String
if context.cpp_source?
buf<< "class _#{full_name(context)} : public sf::#{full_name(context)} {"
buf<< "public:"
buf<< "void* parent;"
end
each do |func|
next unless func.is_a?(CFunction) && !func.visibility.private?
abstr = func.abstract? || func.name(Context::Crystal).starts_with?("on_")
if func.visibility.protected? && !abstr && context.cpp_source? && !func.constructor?
buf<< "using #{full_name(context)}::#{func.name(context)};"
end
next unless abstr
c_params = ["void*"]
cpp_params = [] of String
cpp_args = ["parent"]
cl_params = ["self : Void*"]
cr_args = [] of String
if (typ = func.type)
return_param = CParameter.new("result", typ)
end
(func.parameters + [return_param].compact).each do |param|
cpp_params << "#{param.type.full_name} #{param.name(Context::CPPSource)}" unless param == return_param
if param.type.type.is_a?(CClass)
if param.type.type.full_name == "SoundStream::Chunk" && param.type.reference?
c_params << "Int16**" << "std::size_t*"
cl_params << "#{param.name(Context::CrystalLib)} : Int16**" << "#{param.name(Context::CrystalLib)}_size : LibC::SizeT*"
cpp_args << "(Int16**)&#{param.name(Context::CPPSource)}.samples" << "&#{param.name(Context::CPPSource)}.sampleCount"
else
c_params << "void*"
cl_params << "#{param.name(Context::CrystalLib)} : Void*"
cpp_args << "&" + param.name(Context::CPPSource)
unless param == return_param
unless param.type.is_a?(CNativeType)
cr_args << "#{param.name(Context::CrystalLib)}.as(#{param.type.full_name(Context::Crystal)}*).value"
end
end
end
else
ptr = "#{"*"*param.type.pointer}#{"*" if param.type.reference?}#{"*" if param == return_param}"
c_type = param.type.type.full_name(Context::CHeader) + ptr
c_params << c_type
cl_params << "#{param.name(Context::CrystalLib)} : #{param.type.type.full_name(Context::CrystalLib)}#{ptr}"
cpp_args << "(#{c_type})#{"&" if param == return_param}#{param.name(Context::CPPSource)}"
if param.name(Context::CPPSource) == "sampleCount"
cr_args[-1] = "Slice(Int16).new(samples, sample_count)"
elsif param.name(Context::CPPSource) == "size"
cr_args[-1] = "Slice(UInt8).new(#{cr_args[-1]}.as(UInt8*), #{param.name(Context::CrystalLib)})"
else
cr_args << param.name(Context::CrystalLib) unless param == return_param
end
end
end
callback_name = "#{PREFIX}#{full_name(context).downcase}_#{func.name(Context::CPPSource).downcase}_callback"
if context.cpp_source?
o<< "void (*_#{callback_name})(#{c_params.join(", ")}) = 0;"
o<< "void #{callback_name}(void (*callback)(#{c_params.join(", ")})) {"
o<< "_#{callback_name} = callback;"
o<< "}"
end
if context.cpp_source?
typ = func.type.try &.full_name || "void"
buf<< "virtual #{typ} #{func.name(context)}(#{cpp_params.join(", ")})#{" const" if func.const?} {"
buf<< "#{return_param.type.full_name} result;" if return_param
buf<< "_#{callback_name}(#{cpp_args.join(", ")});"
buf<< "return result;" if return_param
buf<< "}"
end
if context.crystal_lib?
o<< "fun #{callback_name}(callback : (#{cl_params.map(&.split(" : ")[1]).join(", ")} ->))"
end
if context.crystal?
o<< "#{LIB_NAME}.#{callback_name}(->(#{cl_params.join(", ")}) {"
inst = ("self")
o<< "#{"output = " if func.type}#{inst}.as(#{full_name(context)}).#{func.name(context)}(#{cr_args.join(", ")})"
if func.parameters.any? { |param| param.type.full_name(Context::CPPSource) == "SoundStream::Chunk" }
o<< "data.value, data_size.value = output.to_unsafe, LibC::SizeT.new(output.size) if output"
end
if (typ = func.type)
if typ.type.full_name(Context::Crystal) == "Bool"
o<< "result.value = !!output"
elsif typ.type.is_a?(CNativeType)
o<< "result.value = #{typ.type.full_name(Context::Crystal)}.new(output)"
elsif typ.type.full_name == "Vector2f"
o<< "result.as(Vector2f*).value = Vector2f.new(output[0].to_f32, output[1].to_f32)"
else
o<< "result.value = output"
end
end
o<< "})"
end
end
if context.cpp_source?
buf<< "};"
buf.each do |line|
o<< line
end
end
end
if context.crystal?
render_docs(o, qualname)
inh = " < #{inherited_class.not_nil!.name(context)}" if inherited_class
kind = case
when module?
"module"
when struct?
"struct"
else
"class"
end
abstr = "abstract " if abstract? && !module?
parent = self.parent
if parent.is_a?(CClass) && parent.union?
inh = " < #{parent.name(context)}"
abstr = "abstract "
end
o<< "#{abstr}#{kind} #{name(context)}#{inh}"
if class?
o<< "@this : Void*"
end
end
if abstract? && class?
CFunction.new(
name: "parent", type: nil, parameters: [CParameter.new("parent", make_type("void*", nil))] of CParameter, parent: self
).render(context, o)
end
CFunction.new(
"allocate", type: CType.new(self, pointer: 1), parameters: [] of CParameter, static: true, parent: self
).render(context, o)
if none? { |item| item.is_a? CFunction && item.constructor? }
CFunction.new(
name(Context::CPPSource).not_nil!, type: nil, parameters: [] of CParameter, parent: self
).render(context, o)
end
if class? && none? { |item| item.is_a? CFunction && item.destructor? }
CFunction.new(
name: "~#{self.name(Context::CPPSource)}", type: nil, parameters: [] of CParameter, parent: self
).render(context, o)
end
CFunction.new(
name: "free", type: nil, parameters: [] of CParameter, parent: self
).render(context, o)
to_render = Set(CClass).new
todo = [self]
until todo.empty?
to_render.concat(todo)
todo = todo.map { |cls| ([cls.inherited_class] + cls.inherited_modules.map { |m| find_type(m, nil).as?(CClass) }).compact } .flatten
end
done_functions = Set(String).new
union_var = union?
each do |item|
if item.is_a? CVariable
if union_var
if context.crystal?
o<< "@_#{item.name(context)} = uninitialized #{item.type.name(context)}"
o<< "# :nodoc:"
o<< "def to_unsafe()"
o<< "pointerof(@_#{item.name(context)})"
o<< "end"
end
break
end
item.render(context, o, var_only: true)
end
end
each do |item|
if union_var
next if item.is_a?(CVariable)
end
next unless item.render(context, o)
if item.is_a? CFunction
done_functions << item.name(Context::CrystalLib)
end
end
to_render.each do |cls|
cls.each do |item|
if item.is_a?(CFunction)
begin
next if item.destructor? || item.constructor? || (item.abstract? && abstract?) || !item.parent
func = CFunction.new(
name: item.name(Context::CPPSource),
type: item.type, parameters: item.parameters,
static: item.static?, is_abstract: item.abstract?,
visibility: item.visibility, parent: self, docs: [":nodoc:"]
)
func_name = func.name(Context::CrystalLib)
next if done_functions.includes?(func_name)
func.render(context, o)
done_functions << func_name
rescue
end
end
end
end
if context.crystal?
if union_var
union_enum = union_var.type.type.as(CEnum)
union_enum.members.each do |member|
next if member.name(context) == "Count"
inh = name(context)
items.each do |item|
if item.is_a? CClass
if item.docs.join('\n') =~ /\b#{member.name(context)}\b/
inh = item.name(context)
break
end
end
end
member.render_docs(o, qualname + "::" + member.name(Context::Crystal))
o<< "struct #{member.name(context)} < #{inh}"
o<< "@_#{union_var.name(context)} = #{member.full_name(context)}"
o<< "end"
end
end
inherited_modules.each do |mod|
o<< "include #{mod}"
end
unless module? || inh
o<< "# :nodoc:"
o<< "def to_unsafe()"
if struct?
o<< "pointerof(@#{find(&.is_a? CVariable).not_nil!.name(Context::Crystal)}).as(Void*)"
else
o<< "@this"
end
o<< "end"
end
if class?
o<< "# :nodoc:"
o<< "def inspect(io)"
o<< "to_s(io)"
o<< "end"
end
end
if has_module?("Drawable")
%w[RenderTexture RenderWindow RenderTarget].each do |target|
func = CFunction.new("draw", type: nil,
parameters: [CParameter.new("target", make_type("const #{target} &", nil)),
CParameter.new("states", make_type("RenderStates", nil))],
visibility: visibility, parent: self, docs: [":nodoc:"]
)
if context.cpp_source?
o<< "void #{func.name(Context::CrystalLib)}(void* self, void* target, void* states) {"
o<< "((#{target}*)target)->draw(*(#{"_" if abstract?}#{self.full_name(context)}*)self, *(RenderStates*)states);"
o<< "}"
else
func.render(context, o)
end
end
end
unless has_module?("NonCopyable") || has_module?("RenderTarget") || has_module?("AlResource") || module? || abstract?
CFunction.new(@name.not_nil!, type: nil,
parameters: [CParameter.new("copy", CType.new(self, reference: true, const: true))],
visibility: Visibility::Public, parent: self, docs: [":nodoc:"]
).render(context, o)
if context.crystal?
o<< "def dup() : #{name(Context::Crystal)}"
o<< "return #{name(Context::Crystal)}.new(self)"
o<< "end"
end
end
if context.crystal?
o<< "end"
each do |func|
next unless func.is_a? CFunction
next unless (typ = func.const_reference_getter?)
o<< "# :nodoc:"
o<< "class #{typ.full_name(context)}::Reference < #{typ.full_name(context)}"
o<< "def initialize(@this : Void*, @parent : #{name(context)})"
o<< "end"
o<< "def finalize()"
o<< "end"
o<< "def to_unsafe()"
o<< "@this"
o<< "end"
o<< "end"
end
end
end
def union? : CVariable?
if full_name(Context::CPPSource) == "Event"
each do |item|
if item.is_a?(CVariable) && item.visibility.public?
return item
end
end
end
end
def struct? : Bool
return false if module?
return false if inherited_class
return true if STRUCTS.includes? self.full_name
return false if any? { |item| item.is_a?(CVariable) && %w[String std::string].includes?(item.type.full_name) }
any? { |item| item.is_a?(CVariable) && item.visibility.public? }
end
def module? : Bool
return true if MODULE_CLASSES.includes? self.full_name
!items.empty? && none? { |item|
item.is_a?(CFunction) && !item.static? || item.is_a?(CVariable) && item.visibility.public?
}
end
def class? : Bool
!struct? && !module?
end
def abstract? : Bool
(!!union? || any? { |item|
item.is_a?(CFunction) && item.abstract?
})
end
def has_module?(mod : String) : Bool
cls = self
while cls.is_a? CClass
return true if cls.inherited_modules.includes? mod
cls = cls.inherited_class
end
false
end
end
class CNativeType
def initialize(@name : String)
end
def name(context : Context) : String
c_type = cl_type = @name.not_nil!
cr_type = c_type.gsub('<', '(').gsub('>', ')')
case c_type
when "std::string"
c_type = "char*"
cl_type = "LibC::Char*"
cr_type = "String"
when "String"
c_type = "Uint32*"
cl_type = "Char*"
when /\bstd::vector<(.+)>/
if $1 == "std::string"
c_type = "char**"
cl_type = "LibC::Char**"
cr_type = "Array(String)"
elsif $1 == " char"
c_type = "char*"
cl_type = "LibC::Char*"
cr_type = "Array(String)"
else
c_type = "void*"
cl_type = "Void*"
cr_type = "Array(#{$1})"
end
when "std::size_t"
c_type = "std::size_t"
cl_type = cr_type = "LibC::SizeT"
when /^(unsigned )?(int|short)$/
u = "U" if $1?
cl_type = "LibC::#{u}#{$2.capitalize}"
cr_type = "#{u}" + {"int" => "Int32", "short" => "Int16"}[$2]
when /^(Int|Uint)[0-9]+$/
cl_type = cr_type = cl_type.sub("int", "Int")
when "float", "double", "char"
cl_type = "LibC::#{cl_type.capitalize}"
cr_type = {"float" => "Float32", "double" => "Float64", "char" => "UInt8"}[c_type]
when "bool"
c_type = "Int8"
cr_type = cl_type = "Bool"
when "void"
cr_type = cl_type = "Void"
end
case context
when .crystal?
cr_type
when .crystal_lib?
cl_type
when .c_header?
c_type
else
@name.not_nil!
end
end
def full_name(context = Context::CPPSource) : String
name(context)
end
end
class CEnumMember < CItem
def initialize(name : String, @value : String?, *args, **kwargs)
super(name, *args, **kwargs)
end
def name(context : Context) : String
@name.not_nil!
end
def value(context = Context::CPPSource) : String?
@value
end
def render(context : Context, out o : Output)
line = name(context)
if @value
line += " = #{value(context)}"
end
o<< line
end
end
class CEnum < CNamespace
getter members = [] of CEnumMember
def initialize(name : String?, *args, **kwargs)
super(name, *args, **kwargs)
end
def add(member : CEnumMember)
members << member
end
def render(context : Context, out o : Output)
return if visibility.private?
union_enum = (parent.as?(CClass).try &.union?)
if context.crystal?
if @name
render_docs(o, qualname)
if members.map(&.value).compact.any?(&.includes? "<<")
o<< "@[Flags]"
end
o<< "enum #{name(context)}"
end
members.each do |member|
next if member.name(Context::Crystal) == "None" && member.value == "0"
member.render_docs(o, qualname + "::" + member.name(Context::Crystal))
member.render(context, o)
end
if @name
o<< "end"
unless full_name == "Style" || union_enum
o<< "Util.extract #{full_name(context)}"
end
end
end
end
end
class CParameter
def initialize(@name : String, @type : CType, @default : String? = nil)
end
property name : String
property type : CType
property default : String?
def name(context : Context) : String
context.cpp_source? ? @name : @name.underscore.sub(/^(the|mode)_/, "")
end
end
class CFunction < CItem
def initialize(name : String, @type : CType?, @parameters : Array(CParameter),
@static : Bool = false, is_abstract : Bool = false, @const : Bool = false, *args, **kwargs)
@abstract = is_abstract
super(name.gsub(/\b \B/, ""), *args, **kwargs)
end
getter type : CType?
getter parameters : Array(CParameter)
getter? static : Bool
getter? abstract : Bool
getter? const : Bool
def name(context : Context, parent : CNamespace? = @parent) : String
name = @name.not_nil!
name = name.underscore unless context.cpp_source?
unless context.cpp_source?
name = operator_name || constructor_name || destructor_name || name
end
if context.crystal?
name = getter_name || setter_name || name
name = {
"to_string" => "to_s",
">>" => "read",
"<<" => "write",
"BoolType" => "valid?",
}.fetch(name, name)
end
if context.crystal_lib?
if operator?
name = "operator_" + {
"==" => "eq", "!=" => "ne",
"<" => "lt", ">" => "gt",
"<=" => "le", ">=" => "ge",
"+" => "add", "-" => "sub", "*" => "mul", "/" => "div", "%" => "mod",
"[]" => "index", "[]=" => "indexset",
"<<" => "shl", ">>" => "shr",
"BoolType" => "bool",
}[name]
else
name = name.gsub "_", ""
end
if parent
parent_name = parent.full_name(context).not_nil!
name = parent_name.downcase + "_" + name
end
name = PREFIX + name
hash = parameters.map { |param|
identifier_hash(param.type.full_name)
} .join
name += "_#{hash}" unless hash.empty? || @name == "parent"
end
name
end
def qualname(parent : CNamespace? = @parent) : String
parts = [parent.try(&.qualname) || "SF", name(Context::Crystal)]
parts.compact.join(static? ? "." : "#")
end
def getter_name : String?
name = @name.not_nil!.underscore
case name
when .starts_with? "get_"
parameters.size == 0 ? name[4..-1] : name
when .starts_with? "is_"
name[3..-1] + "?"
when .starts_with? "has_"
name[4..-1] + "?"
else
nil
end
end
def setter_name : String?
return nil if parameters.size > 1
name = @name.not_nil!.underscore
if name.starts_with? "set_"
name[4..-1] + "="
end
end
def operator_name : String?
if @name =~ /operator\b *(.+)/
$1
end
end
def operator? : Bool
!!operator_name
end
private def constructor_name : String?
if @name == parent.try &.name(Context::CPPSource)
"initialize"
end
end
def constructor?
!!constructor_name
end
private def destructor_name : String?
if @name == "~#{parent.try &.name(Context::CPPSource)}"
"finalize"
end
end
def destructor?
!!destructor_name
end
def reference_getter? : CType?
if (typ = self.type) && typ.type.as?(CClass).try &.class? && (typ.reference? && !typ.const? || typ.pointer > 0) && getter_name
typ
end
end
def const_reference_getter? : CType?
if (typ = self.type) && typ.type.as?(CClass).try &.class? && (typ.reference? && typ.const?) && getter_name
typ
end
end
def reference_setter? : CType?
if @name.not_nil!.underscore.starts_with?("set_") && !parameters.empty?
typ = parameters[0].type
if typ.type.as?(CClass).try &.class? || typ.type.is_a?(CClass) && typ.pointer > 0
typ
end
end
end
def reference_var : String?
name = if reference_setter?
@name.not_nil!.underscore[4..-1]
elsif reference_getter?
getter_name
else
return
end
"@_#{parent.try &.full_name(Context::CrystalLib).not_nil!.downcase}_#{name}"
end
def render(context : Context, out o : Output, parent : CNamespace? = self.parent)
cls = parent.as? CClass
return if visibility.private?
return if context.crystal? && {"allocate", "free", "parent"}.includes? @name
return unless visibility.public? || (cls && (cls.abstract? || %w[SoundStream SoundRecorder].includes?(cls.inherited_class.try &.full_name)) && cls.class?) || constructor?
if (operator_name || "").downcase.starts_with?("bool")
@type = make_type("bool", nil)
else
return if (operator_name.try &.=~ %r(^([+\-*/%]?=|[a-zA-Z:]+)$))
end
return if @docs[0]? == "\\brief Copy constructor"
if parameters.any? { |param| param.type.full_name =~ /^[A-Z]$/ }
return unless parameters.map(&.name) == ["function", "argument"]
end
return if @name.try &.starts_with? "setUniform"
cr_params = [] of String
cr_args = [] of String
cl_params = [] of String
c_params = [] of String
cpp_args = [] of String
if !static? && cls
c_params << "void* self"
cl_params << "self : Void*"
cr_args << "to_unsafe"
end
if cls
if destructor? && cls.module?
return
end
name = cls.full_name
name = "_#{name}" if cls.abstract? && cls.class?
if constructor?
if (cls.module? || cls.union?)
return
end
cpp_obj = "new(self) #{name}".sub /[A-Z]\w*$/, "" # avoid name duplication
elsif static?
cpp_obj = "#{name}::"
else
cpp_obj = "((#{name}*)self)->"
end
end
if operator_name == "[]" && !self.type.try &.const?
@name = "operator []="
@parameters << CParameter.new("value", CType.new(self.type.not_nil!.type))
@type = nil
end
if %w[<< >>].includes? operator_name
@type = nil
if parameters.any? { |param| %w[char String].includes? param.type.full_name(Context::CPPSource) }
return
end
end
return_params = [] of CParameter
extra_return_params = [] of CParameter
if (type = self.type)
extra = (type.reference? && type.const? && type.type.as?(CClass).try &.class? ? 1 : 0)
type = CType.new(type: type.type, reference: type.reference?,
pointer: type.pointer + extra, const: type.const?)