-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathtypes.lua
2769 lines (2510 loc) · 88.7 KB
/
types.lua
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
--[[
Types module
The types module define classes for all the primitive types in Nelua.
Also defines some utilities functions for working with types.
This module is always available in the preprocessor in the `types` variable.
]]
local class = require 'nelua.utils.class'
local tabler = require 'nelua.utils.tabler'
local iters = require 'nelua.utils.iterators'
local traits = require 'nelua.utils.traits'
local stringer = require 'nelua.utils.stringer'
local sstream = require 'nelua.utils.sstream'
local metamagic = require 'nelua.utils.metamagic'
local bn = require 'nelua.utils.bn'
local except = require 'nelua.utils.except'
local shaper = require 'nelua.utils.shaper'
local Attr = require 'nelua.attr'
local ASTNode = require 'nelua.astnode'
local types = {}
-- These are set by types.set_typedefs when typedefs file is loaded.
local typedefs, primtypes
--------------------------------------------------------------------------------
-- Type
--
-- Type is the base class that all other types are derived form.
local Type = class()
types.Type = Type
-- Define the shape of all fields used in the type.
-- Use this as a reference to know all used fields in the Type class by the compiler.
Type.shape = shaper.shape {
-- Size of the type at runtime in bytes.
size = shaper.integer:is_optional(),
-- Size of the type at runtime in bits.
bitsize = shaper.integer:is_optional(),
-- Alignment for the type in bytes.
align = shaper.integer:is_optional(),
-- Short name of the type, e.g. 'int64', 'record', 'enum' ...
name = shaper.string,
-- Nickname for the type, usually it's the first identifier name that defined it in the sources.
-- The nickname is used to generate pretty names for compile time type errors,
-- also used to assist the compiler generating pretty code names in C.
nickname = shaper.string:is_optional(),
-- The actual name of the type used in the code generator when emitting C code.
codename = shaper.string,
-- Fixed custom codename used in <codename> annotation.
fixedcodename = shaper.string:is_optional(),
-- Symbol that defined the type, not applicable for primitive types.
symbol = shaper.symbol:is_optional(),
-- Node that defined the type.
node = shaper.astnode:is_optional(),
-- Unary operators defined for the type.
unary_operators = shaper.table,
-- Binary operators defined for the type.
binary_operators = shaper.table,
-- Table of meta fields (global methods/variables of the type).
metafields = shaper.table:is_optional(),
-- A generic type that the type can represent when used as generic.
generic = shaper.type:is_optional(),
-- Whether the code generator should omit the type declaration.
nodecl = shaper.optional_boolean,
-- Whether the compiler should never omit unused types.
nodce = shaper.optional_boolean,
-- Whether the code generator should import the type from C.
cimport = shaper.optional_boolean,
-- Whether the type was marked as incomplete imported struct/union.
cincomplete = shaper.optional_boolean,
-- Whether to emit typedef for a C imported structs.
ctypedef = shaper.optional_boolean,
-- Whether an empty type was referenced.
emptyrefed = shaper.optional_boolean,
-- Whether the scope is using fields from the type. (e.g. enum fields)
using = shaper.optional_boolean,
-- Whether the type can be copied, that is, passed by value.
nocopy = shaper.optional_boolean,
-- Marked when declaring a type without its definition.
forwarddecl = shaper.optional_boolean,
forwarddefn = shaper.optional_boolean,
-- C header that the code generator should include when using the type.
cinclude = shaper.string:is_optional(),
-- The value passed in <aligned(X)> annotation, see also align.
aligned = shaper.integer:is_optional(),
-- Whether the type can have user defined nickname, true for user defined types.
is_nameable = shaper.optional_boolean,
-- Whether the type can be evaluated to false when casting to a boolean.
is_falseable = shaper.optional_boolean,
-- Whether the type can turn represents a string (e.g. string and cstring).
is_stringy = shaper.optional_boolean,
-- Whether the type represents a contiguous buffer (e.g. arrays, spans and vector in the lib).
is_contiguous = shaper.optional_boolean,
-- Whether the type represents a container buffer (e.g. arrays, spans, vector and list in the lib).
is_container = shaper.optional_boolean,
-- Whether the type uses 1-based indexing (e.g. sequence and table).
is_oneindexing = shaper.optional_boolean,
-- Whether the type is a compile time type (e.g concepts, generics)
is_comptime = shaper.optional_boolean,
-- Whether the type is used as a polymorphic argument in poly functions.
is_polymorphic = shaper.optional_boolean,
-- Whether the type cannot be a l-value.
is_nolvalue = shaper.optional_boolean,
-- Whether the type is a numeric scalar (e.g. float, integrals and enums).
is_scalar = shaper.optional_boolean,
-- Whether the type can perform arithmetic operations (e.g. sum, add, mul, ...).
is_arithmetic = shaper.optional_boolean,
-- Whether the type is a floating point number type (fractional numbers).
is_float = shaper.optional_boolean,
-- Whether the type is an integral type (whole numbers).
is_integral = shaper.optional_boolean,
-- Whether the type can have a negative sign (e.g. int64, float64, ...).
is_signed = shaper.optional_boolean,
-- Whether the type is a procedure (e.g. a function or a poly function).
is_procedure = shaper.optional_boolean,
-- Whether the type is not addressable in memory (e.g. type, concept, ...)
is_unpointable = shaper.optional_boolean,
-- Whether the type is composed by fields (record or union).
is_composite = shaper.optional_boolean,
-- Whether the type aggregates other types (record, union and arrays).
is_aggregate = shaper.optional_boolean,
-- Weather the runtype type does not store anything (empty records, union and arrays).
is_empty = shaper.optional_boolean,
-- Whether the type hold multiple arguments.
is_multipleargs = shaper.optional_boolean,
-- Booleans for checking the underlying type (scalar types),
is_float32 = shaper.optional_boolean,
is_float64 = shaper.optional_boolean,
is_float128 = shaper.optional_boolean,
is_int8 = shaper.optional_boolean,
is_int16 = shaper.optional_boolean,
is_int32 = shaper.optional_boolean,
is_int64 = shaper.optional_boolean,
is_int128 = shaper.optional_boolean,
is_isize = shaper.optional_boolean,
is_uint8 = shaper.optional_boolean,
is_uint16 = shaper.optional_boolean,
is_uint32 = shaper.optional_boolean,
is_uint64 = shaper.optional_boolean,
is_uint128 = shaper.optional_boolean,
is_usize = shaper.optional_boolean,
is_cschar = shaper.optional_boolean,
is_cshort = shaper.optional_boolean,
is_cint = shaper.optional_boolean,
is_clong = shaper.optional_boolean,
is_clonglong = shaper.optional_boolean,
is_cptrdiff = shaper.optional_boolean,
is_cchar = shaper.optional_boolean,
is_cuchar = shaper.optional_boolean,
is_cushort = shaper.optional_boolean,
is_cuint = shaper.optional_boolean,
is_culong = shaper.optional_boolean,
is_culonglong = shaper.optional_boolean,
is_csize = shaper.optional_boolean,
is_cfloat = shaper.optional_boolean,
is_cdouble = shaper.optional_boolean,
is_clongdouble = shaper.optional_boolean,
-- Booleans for checking the underlying type (primitive types).
is_any = shaper.optional_boolean,
is_array = shaper.optional_boolean,
is_auto = shaper.optional_boolean,
is_boolean = shaper.optional_boolean,
is_concept = shaper.optional_boolean,
is_overload = shaper.optional_boolean,
is_facultative = shaper.optional_boolean,
is_enum = shaper.optional_boolean,
is_function = shaper.optional_boolean,
is_generic = shaper.optional_boolean,
is_nilable = shaper.optional_boolean,
is_niltype = shaper.optional_boolean,
is_pointer = shaper.optional_boolean,
is_polyfunction = shaper.optional_boolean,
is_record = shaper.optional_boolean,
is_union = shaper.optional_boolean,
is_stringview = shaper.optional_boolean, -- deprecated
is_table = shaper.optional_boolean,
is_type = shaper.optional_boolean,
is_varanys = shaper.optional_boolean,
is_varargs = shaper.optional_boolean,
is_cvarargs = shaper.optional_boolean,
is_void = shaper.optional_boolean,
is_generic_pointer = shaper.optional_boolean,
is_cstring = shaper.optional_boolean,
is_acstring = shaper.optional_boolean,
is_byte_pointer = shaper.optional_boolean,
is_array_pointer = shaper.optional_boolean,
is_bytearray_pointer = shaper.optional_boolean,
is_unbounded_pointer = shaper.optional_boolean,
is_bounded_pointer = shaper.optional_boolean,
is_unbounded_array = shaper.optional_boolean,
is_multidim_array = shaper.optional_boolean,
is_cvalist = shaper.optional_boolean,
-- Booleans for checking the underlying type (lib types).
is_allocator = shaper.optional_boolean,
is_string = shaper.optional_boolean,
is_span = shaper.optional_boolean,
is_vector = shaper.optional_boolean,
is_sequence = shaper.optional_boolean,
is_list = shaper.optional_boolean,
is_hashmap = shaper.optional_boolean,
is_filestream = shaper.optional_boolean,
is_time_t = shaper.optional_boolean,
is_clock_t = shaper.optional_boolean,
is_wchar_t = shaper.optional_boolean,
}
-- This is used to check if a table is a 'bn'.
Type._type = true
-- Lists of operators defined for all types.
Type.unary_operators = {}
Type.binary_operators = {}
function Type:_init(name, size)
self.name = name
if size == nil then
self.size = 0
elseif size then
self.size = size
end
if self.size then
self.bitsize = self.size * 8
end
-- set the default alignment for this type,
-- usually the default alignment on primitive types is the primitive size itself
if not self.align and self.size then
self.align = self.size
end
if self.align then
self.align = math.min(self.align, typedefs.maxalign)
end
-- generate a codename in case not set yet
if not self.codename then
self.codename = 'nl' .. self.name
end
-- set unary and binary operators tables
local mt = getmetatable(self)
self.unary_operators = setmetatable({}, {__index = mt.unary_operators})
self.binary_operators = setmetatable({}, {__index = mt.binary_operators})
end
-- Set a new codename for this type, storing it in the typeid table.
function Type:set_codename(codename)
self.codename = codename
end
-- Set a nickname for this type if not set yet.
function Type:suggest_nickname(nickname)
if nickname == 'T' then -- T is used for many generics, let's ignore it
return false
end
if not self.nickname and self.is_nameable then
self.nickname = nickname
return true
end
return false
end
-- Return description for type as a string.
function Type:typedesc()
return self.name
end
-- Helper to perform an operation returning the resulting type, compile time value and error.
local function perform_op_from_list(self, op, ...)
local type, value, err
if traits.is_function(op) then
-- op is a function, get the results by running it
type, value, err = op(...)
else
-- op must be fixed type or nil
type, value = op, nil
end
if not type and self.is_any then
-- operations on any values must always results in any too
type, value = self, nil
end
return type, value, err
end
-- Perform an unary operation on attr returning the resulting type, compile time value and error.
function Type:unary_operator(opname, attr)
local type, value, err = perform_op_from_list(self, self.unary_operators[opname], self, attr)
if not type and not err then -- no resulting type, but no error, thus generate one
err = string.format("invalid operation for type '%s'", self)
end
return type, value, err
end
-- Perform a binary operation on attrs returning the resulting type, compile time value and error.
function Type:binary_operator(opname, rtype, lattr, rattr)
local type, value, err = perform_op_from_list(self, self.binary_operators[opname], self, rtype, lattr, rattr)
if not type and not err then -- try binary operator on the right type
type, value, err = perform_op_from_list(rtype, rtype.binary_operators[opname], self, rtype, lattr, rattr)
end
if not type and not err then -- no error, thus generate one
err = string.format("invalid operation between types '%s' and '%s'", self, rtype)
end
return type, value, err
end
-- Get the desired type when converting this type from another type.
function Type:get_convertible_from_type(type, explicit, fromcall)
if self == type then
-- the type itself
return self
elseif type.is_any then
-- anything can be converted to and from `any`
return self
elseif type.is_niltype and not explicit and fromcall then
-- call arguments can be converted from `niltype`
return self
end
local msg = string.format("no viable type conversion from '%s' to '%s'", type, self)
if type.nickname and type.is_procedure then
msg = msg..'\n\t'..string.format("where '%s' is also known as '%s'", type.nickname, type:typedesc())
end
if self.nickname and self.is_procedure then
msg = msg..'\n\t'..string.format("where '%s' is also known as '%s'", self.nickname, self:typedesc())
end
return false, msg
end
-- Get the desired type when converting this type from an attr.
function Type:get_convertible_from_attr(attr, ...)
return self:get_convertible_from_type(attr.type, ...)
end
-- Checks if this type is convertible from another type.
function Type:is_convertible_from_type(type, ...)
local ok, err = self:get_convertible_from_type(type, ...)
return not not ok, err
end
-- Checks if this type is convertible from an attr.
function Type:is_convertible_from_attr(attr, ...)
local ok, err = self:get_convertible_from_attr(attr, ...)
return not not ok, err
end
-- Checks if this type is convertible from a node, type or attr.
function Type:is_convertible_from(what, ...)
if traits.is_astnode(what) then
return self:is_convertible_from_attr(what.attr, ...)
elseif traits.is_type(what) then
return self:is_convertible_from_type(what, ...)
else --luacov:disable
assert(what._attr)
return self:is_convertible_from_attr(what, ...)
end --luacov:enable
end
-- Wrap a compile time value to be fitted on this type.
function Type.wrap_value(_, value)
return value
end
-- Returns the resulting type when trying to fit a compile time value into this type.
-- Promoting to a larger type when required.
function Type.promote_type_for_value() return nil end
-- Returns the resulting type when mixing this type with another type.
function Type:promote_type(type)
return self == type and self or nil
end
-- Checks if this type can initialize from the attr (succeeds only for compile time attrs).
function Type:is_initializable_from_attr(attr)
return (attr.comptime and self == attr.type) or attr.ctopinit
end
-- Checks if this type equals to another type.
-- Usually this is overwritten by derived types, but this is a fallback implementation.
function Type:is_equal(type)
return type.codename == self.codename
end
-- Give the underlying type when implicit dereferencing this type.
function Type:implicit_deref_type()
return self
end
-- Checks if the type underlying structure is really defined (related to forwarddecl annotation).
function Type:is_defined()
return not self.forwarddecl or self.forwarddefn
end
-- Checks if this type is pointing to the subtype.
function Type.is_pointer_of() return false end
-- Checks if this type is an array of the subtype.
function Type.is_array_of() return false end
-- Checks if this type has pointers, used by the garbage collector.
function Type.has_pointer() return false end
-- Checks if this type can be represented as a contiguous array of the subtype.
function Type.is_contiguous_of() return false end
-- Return a pretty string representing the type.
-- Usually returns the type's nickname when available or a verbose description otherwise.
function Type:__tostring()
if self.nickname then
-- use the nickname when available because it's compact and prettier
return self.nickname
else
-- use the typedesc when no nickname is available
-- however this can be too verbose for complex types
return self:typedesc()
end
end
-- Compare if two types are equal.
function Type.__eq(t1, t2)
if getmetatable(t1) == getmetatable(t2) then
return t1:is_equal(t2)
end
return false
end
Type.unary_operators['not'] = function(_, attr)
local reval
if attr.value ~= nil then
reval = false
end
return primtypes.boolean, reval
end
Type.unary_operators.ref = function(ltype, lattr)
local lval = lattr.value
if lval == nil then
if not ltype.is_unpointable then
return types.PointerType(ltype)
else
return nil, nil, string.format('cannot reference not addressable type "%s"', ltype)
end
else
if ltype.is_aggregate then
return types.PointerType(ltype)
end
return nil, nil, string.format('cannot reference compile time value of type "%s"', ltype)
end
end
Type.binary_operators.eq = function(ltype, rtype, lattr, rattr)
if ltype.is_comptime or rtype.is_comptime then
return primtypes.boolean, ltype == rtype and lattr.value == rattr.value
end
local reval
local lval, rval = lattr.value, rattr.value
if lval ~= nil and rval ~= nil then
reval = lval == rval
end
return primtypes.boolean, reval
end
Type.binary_operators.ne = function(ltype, rtype, lattr, rattr)
local retype, reval = ltype:binary_operator('eq', rtype, lattr, rattr)
if reval ~= nil then
reval = not reval
end
return retype, reval
end
Type.binary_operators['and'] = function(ltype, rtype, lattr, rattr)
local reval
local retype = types.promote_type_for_attrs(lattr, rattr) or ltype:promote_type(rtype) or primtypes.any
local lval, rval = lattr.value, rattr.value
if retype.is_boolean and lval ~= nil and rval ~= nil then
reval = not not (lval and rval)
end
return retype, reval
end
Type.binary_operators['or'] = function(ltype, rtype, lattr, rattr)
local reval
local retype = types.promote_type_for_attrs(lattr, rattr) or ltype:promote_type(rtype) or primtypes.any
local lval, rval = lattr.value, rattr.value
if retype.is_boolean and lval ~= nil and rval ~= nil then
reval = lval or rval
end
return retype, reval
end
--------------------------------------------------------------------------------
-- Type utilities
-- Counter used to generate unique codenames.
local gencodename_uid = 0
-- Generate a unique codename based on the type name and a node position.
function types.gencodename(name, node)
local uid
local srcname
if node then
uid = node.uid
srcname = node.src and node.src.name or ''
else
gencodename_uid = gencodename_uid + 1
uid = gencodename_uid
srcname = '__nonode__'
end
-- make a hash combining the type name, code source file and uid
local key = string.format('%s%s%d', name, srcname, uid)
-- take hash of the key
local hash = stringer.hash(key, 12)
-- combine the name and hash to generate our codename
return string.format('%s_%s', name, hash)
end
-- Used internally, set the typedefs and primtypes locals.
-- This exists because typedefs and types modules have recursive dependency on each other.
function types.set_typedefs(t)
typedefs = t
primtypes = t.primtypes
end
-- Make a new type class derived from base type class.
-- Unary and binary operators are inherited.
function types.typeclass(base)
if not base then
base = Type
end
local klass = class(base)
klass.unary_operators = {}
klass.binary_operators = {}
metamagic.setmetaindex(klass.unary_operators, base.unary_operators)
metamagic.setmetaindex(klass.binary_operators, base.binary_operators)
return klass
end
-- Promote all types from a list to a single common type.
-- Used on type resolution.
function types.find_common_type(possibletypes)
if not possibletypes then return end
local commontype = possibletypes[1]
for i=2,#possibletypes do
commontype = commontype:promote_type(possibletypes[i])
if not commontype then -- no common type found
return nil
end
end
return commontype -- found the common type
end
-- Convert a list of nodes holding a type to a list of the holding types.
function types.typenodes_to_types(nodes)
local typelist = {}
for i=1,#nodes do
local nodeattr = nodes[i].attr
assert(nodeattr.type._type and nodeattr.value)
typelist[i] = nodeattr.value
end
if #typelist == 1 and typelist[1].is_void then
-- single void type means no returns
typelist = {}
end
return typelist
end
-- Convert a list of nodes to a list of types.
function types.nodes_to_types(nodes)
local typelist = {}
for i=1,#nodes do
local nodetype = nodes[i].attr.type
assert(nodetype)
typelist[i] = nodetype
end
if #typelist == 1 and typelist[1].is_void then
-- single void type means no returns
typelist = {}
end
return typelist
end
-- Convert a list of argument nodes into a list of argument types.
-- This consider if last argument is a function call.
-- Returns nil if need to wait type resolution to complete.
function types.argtypes_from_argnodes(argnodes, wantedlen)
local nargs = #argnodes
local argtypes = {}
for i=1,nargs do
local argtype = argnodes[i].attr.type
if not argtype then return end -- cannot complete evaluation yet
argtypes[i] = argtype
end
if nargs > 0 and (not wantedlen or nargs < wantedlen) then
local argnode = argnodes[nargs]
local lastattr = argnode.attr
if not lastattr.type then return end -- cannot complete evaluation yet
local calleetype = lastattr.calleetype
if calleetype and not argnode.is_Paren then
if calleetype.is_any then --luacov:disable
if wantedlen then
for i=nargs,wantedlen do
argtypes[i] = primtypes.any
end
end
-- luacov:enable
elseif calleetype.is_procedure then -- is a call
local rettypes = calleetype.rettypes
for i=2,#rettypes do
argtypes[nargs+i-1] = calleetype.rettypes[i]
if wantedlen and #argtypes >= wantedlen then -- has enough arguments
break
end
end
end
end
end
return argtypes
end
-- Convert a list of attrs to a list of its types.
function types.attrs_to_types(attrs)
local typelist = {}
for i=1,#attrs do
typelist[i] = attrs[i].type
end
return typelist
end
-- Check and get last multiple arguments type from a list of attrs.
function types.get_multiple_argtype_from_attrs(attrs)
local lastargattr = attrs[#attrs]
if lastargattr then
local lastargtype = lastargattr.type
if lastargtype and lastargtype.is_multipleargs then
return lastargtype
end
end
end
-- Checks if a list of types has no `auto` type.
function types.are_types_resolved(typelist)
for i=1,#typelist do
if typelist[i].is_auto then
return false
end
end
return true
end
-- Promote compile time attrs to a common type.
function types.promote_type_for_attrs(lattr, rattr)
if not lattr.untyped and rattr.comptime and rattr.untyped then
return lattr.type:promote_type_for_value(rattr.value)
elseif not rattr.untyped and lattr.comptime and lattr.untyped then
return rattr.type:promote_type_for_value(lattr.value)
end
end
-- Check whether the type is a primitive type.
function types.is_primitive_type(type)
return primtypes[type.nickname or type.name] == type
end
--------------------------------------------------------------------------------
-- Void type
--
-- Void type is more used internally to represent an empty type,
-- and also to represent the void type from C.
local VoidType = types.typeclass()
types.VoidType = VoidType
VoidType.nodecl = true
VoidType.is_nolvalue = true
VoidType.is_comptime = true
VoidType.is_void = true
function VoidType:_init(name)
Type._init(self, name, 0)
end
--------------------------------------------------------------------------------
-- Auto Type
--
-- The auto type is a placeholder type to inform the compiler that the
-- type should be deduced right away from another symbol type.
-- It's commonly used in polymorphic functions arguments.
local AutoType = types.typeclass()
types.AutoType = AutoType
AutoType.is_auto = true
AutoType.nodecl = true
AutoType.is_comptime = true
AutoType.is_nilable = true
AutoType.is_unpointable = true
AutoType.is_polymorphic = true
function AutoType:_init(name)
Type._init(self, name, 0)
end
-- Get the desired type when converting this type from another type.
function AutoType.get_convertible_from_type(_, type)
-- the auto type can convert to anything
return type
end
--------------------------------------------------------------------------------
-- Type Type
--
-- The 'type' type is the type of a type.
local TypeType = types.typeclass()
types.TypeType = TypeType
TypeType.is_type = true
TypeType.is_comptime = true
TypeType.is_unpointable = true
TypeType.is_polymorphic = true
function TypeType:_init(name)
Type._init(self, name, 0)
end
-- Length operator for the type type, it returns the size of the type in bytes.
TypeType.unary_operators.len = function(_, attr)
local reval
local holdedtype = attr.value
if holdedtype and holdedtype.size then
reval = bn.new(holdedtype.size)
end
return primtypes.isize, reval
end
--------------------------------------------------------------------------------
-- Niltype Type
--
-- The niltype is the type of 'nil'.
local NiltypeType = types.typeclass()
types.NiltypeType = NiltypeType
NiltypeType.is_niltype = true
NiltypeType.is_nilable = true
NiltypeType.is_falseable = true
NiltypeType.is_unpointable = true
NiltypeType.is_empty = true
function NiltypeType:_init(name, size)
Type._init(self, name, size)
end
-- Get the desired type when converting this type from another type.
function NiltypeType:get_convertible_from_type(type, explicit, fromcall)
if type.is_void then
return true
end
return Type.get_convertible_from_type(self, type, explicit, fromcall)
end
-- Negation operator for niltype type.
NiltypeType.unary_operators['not'] = function()
return primtypes.boolean
end
--------------------------------------------------------------------------------
-- Nilptr Type
--
-- The nilptr is the type of 'nilptr'. Used when working with pointers.
local NilptrType = types.typeclass()
types.NilptrType = NilptrType
NilptrType.is_nolvalue = true
NilptrType.is_nilptr = true
NilptrType.is_falseable = true
NilptrType.is_unpointable = true
function NilptrType:_init(name, size)
Type._init(self, name, size)
end
-- Returns the resulting type when mixing this type with another type.
function NilptrType:promote_type(type)
if type.is_pointer or type.is_function then
-- preserve pointer or function types
return type
end
return Type.promote_type(self, type)
end
-- Negation operator for nilptr type.
NilptrType.unary_operators['not'] = function()
return primtypes.boolean
end
--------------------------------------------------------------------------------
-- Boolean Type
--
-- The boolean type is the type for 'true' and 'false'.
local BooleanType = types.typeclass()
types.BooleanType = BooleanType
BooleanType.is_boolean = true
BooleanType.is_atomicable = true
BooleanType.is_falseable = true
function BooleanType:_init(name, size)
Type._init(self, name, size)
end
function BooleanType:get_convertible_from_type()
-- anything is convertible to a boolean
return self
end
-- Negation operator for boolean type.
BooleanType.unary_operators['not'] = function(ltype, lattr)
local lval = lattr.value
local reval
if lval ~= nil then -- compile time value
reval = not lval
end
return ltype, reval
end
--------------------------------------------------------------------------------
-- Any Type
--
-- The any type is a special type that can store a runtime value of any type.
local AnyType = types.typeclass()
types.AnyType = AnyType
AnyType.is_any = true
AnyType.is_falseable = true
AnyType.sideeffect = true
AnyType.shape = shaper.fork_shape(Type.shape, {
sideeffect = shaper.optional_boolean,
})
function AnyType:_init(name, size)
Type._init(self, name, size)
end
-- Get the desired type when converting this type from another type.
function AnyType:get_convertible_from_type()
-- anything can convert to an any
return self
end
-- Checks if this type has pointers, used by the garbage collector.
function AnyType.has_pointer() return true end
function AnyType.get_return_type() --luacov:disable
return primtypes.any
end --luacov:enable
--------------------------------------------------------------------------------
-- Varanys Type
--
-- The varanys type is used only for the last return type of functions that
-- can return a variable number of anys at runtime.
local VaranysType = types.typeclass(AnyType)
types.VaranysType = VaranysType
VaranysType.is_varanys = true
VaranysType.is_nilable = true
VaranysType.is_multipleargs = true
VaranysType.is_nolvalue = true
function VaranysType:_init(name, size)
Type._init(self, name, size)
end
--------------------------------------------------------------------------------
-- Varargs Type
--
-- The varargs type is used for the last argument type of polymorphic functions
-- that can have variable number of arguments.
local VarargsType = types.typeclass()
types.VarargsType = VarargsType
VarargsType.is_varargs = true
VarargsType.is_multipleargs = true
VarargsType.is_nolvalue = true
VarargsType.is_polymorphic = true
function VarargsType:_init(name, size)
Type._init(self, name, size)
end
--------------------------------------------------------------------------------
-- CVarargs Type
--
-- The cvarargs type is used for the last argument type of C imported functions
-- that can have variable number of arguments.
local CVarargsType = types.typeclass()
types.CVarargsType = CVarargsType
CVarargsType.is_cvarargs = true
CVarargsType.is_multipleargs = true
CVarargsType.is_nolvalue = true
function CVarargsType:_init(name, size)
Type._init(self, name, size)
end
--------------------------------------------------------------------------------
-- Scalar Type
--
-- The scalar type is used as a base type for creating the Integral and Float types.
-- Scalar types can perform arithmetic operations,
-- like addition, subtraction, multiplication, division, etc.
local ScalarType = types.typeclass()
types.ScalarType = ScalarType
ScalarType.is_arithmetic = true
ScalarType.is_scalar = true
ScalarType.is_atomicable = true
ScalarType.get_convertible_from_type = Type.get_convertible_from_type
function ScalarType:_init(name, size)
Type._init(self, name, size)
end
-- Checks if this type can initialize from the attr (succeeds only for compile time attrs).
function ScalarType:is_initializable_from_attr(attr)
if attr.comptime and attr.untyped and attr.type and attr.type.is_scalar then
-- initializing from an untyped compile time scalar is always possible
return true
end
return Type.is_initializable_from_attr(self, attr)
end
-- Negation operator for scalar types.
ScalarType.unary_operators.unm = function(ltype, lattr)
local reval
local retype = ltype
local lval = lattr.value
if lval then -- is compile time value
reval = -lval
retype = ltype:promote_type_for_value(reval)
end
return retype, reval
end
-- Equality operator from scalar types.
ScalarType.binary_operators.eq = function(ltype, rtype, lattr, rattr)
local reval
if lattr == rattr and not ltype.is_float then
-- same symbol and not a float, we can optimize away and return always true
-- floats are ignored because x == x is false when x is NaN
return primtypes.boolean, true
end
if rtype.is_scalar then
local lval, rval = lattr.value, rattr.value
if lval and rval then -- both are compile time values
reval = bn.eq(lval, rval)
end
else
-- equality is always false when comparing another type
reval = false
end
return primtypes.boolean, reval
end
-- Helper to create an comparison operation functions for scalar type.
local function make_arith_cmpop(cmpfunc)
return function(ltype, rtype, lattr, rattr)
if ltype.is_scalar and rtype.is_scalar then
-- we can optimize away the operation when the attr is the same and not a float
-- float are ignored because x <= x is false when x is NaN
local same = lattr == rattr and not ltype.is_float
local reval = cmpfunc(lattr.value, rattr.value, same)
return primtypes.boolean, reval
end
end
end
-- Implement all the scalar comparison operations.
ScalarType.binary_operators.le = make_arith_cmpop(function(a,b,same)
if same then
return true
elseif a and b then
return a <= b
end
end)
ScalarType.binary_operators.ge = make_arith_cmpop(function(a,b,same)
if same then
return true
elseif a and b then
return a >= b
end
end)
ScalarType.binary_operators.lt = make_arith_cmpop(function(a,b,same)
if same then
return false
elseif a and b then
return a < b