-
-
Notifications
You must be signed in to change notification settings - Fork 63
/
types.lua
2394 lines (2141 loc) · 77.4 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 config = require 'nelua.configer'.get()
local ASTNode = require 'nelua.astnode'
local types = {}
-- Size of CPU word in bits.
local cpusize = config.cpu_bits // 8
-- Counter that increment on every new defined type that are fundamentally different.
local typeid_counter = 0
-- Table of type's id by its codename.
local typeid_by_codename = {}
-- 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 {
-- Unique identifier for the type, used when needed for runtime type information.
id = shaper.integer,
-- Size of the type at runtime in bytes.
size = shaper.integer,
-- Size of the type at runtime in bits.
bitsize = shaper.integer,
-- Alignment for the type in bytes.
align = shaper.integer,
-- 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,
-- 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 code generator should import the type from C.
cimport = shaper.optional_boolean,
-- Whether to emit typedef for a C imported structs.
ctypedef = shaper.optional_boolean,
-- Marked when declaring a type without its definition.
forwarddecl = 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 is a primitive type, true for non user defined types.
is_primitive = shaper.optional_boolean,
-- Whether the type can turn represents a string (e.g. stringview, 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,
-- Weather 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 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,
-- Weather the type is composed by fields (record or union).
is_composite = shaper.optional_boolean,
-- Booleans for checking the underlying type (arithmetic 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,
-- 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_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,
is_table = shaper.optional_boolean,
is_type = shaper.optional_boolean,
is_varanys = shaper.optional_boolean,
is_void = shaper.optional_boolean,
is_generic_pointer = shaper.optional_boolean,
is_cstring = shaper.optional_boolean,
-- Booleans for checking the underlying type (lib types).
is_allocator = shaper.optional_boolean,
is_resourcepool = 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,
-- TODO: remove this, because it was deprecated
is_copyable = shaper.optional_boolean,
is_destroyable = 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
self.size = size or 0
self.bitsize = self.size * 8
-- set the default alignment for this type,
-- usually the default alignment on primitive types is the primitive size itself
if not self.align then
self.align = self.size
end
-- generate a codename in case not set yet
if not self.codename then
self.codename = 'nl' .. self.name
end
-- generate an unique id for this type in case not generated yet for this codename
local id = typeid_by_codename[self.codename]
if not id then -- generate an id
id = typeid_counter
typeid_counter = typeid_counter + 1
typeid_by_codename[self.codename] = id
end
self.id = id
-- 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
local id = typeid_by_codename[codename]
if not id then
typeid_by_codename[codename] = self.id
elseif id ~= self.id then
-- id for the codename already exists,
-- this happens when changing codename after a type is declared like in
-- the <codename> annotation, hijack this type id so is_equal works
self.id = id
end
end
-- Set a nickname for this type if not set yet.
function Type:suggest_nickname(nickname)
if self.nickname then -- nickname already set
return false
end
if self.is_primitive then -- changing nicknames for primitives is not allowed
return false
end
self.nickname = nickname
return true
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, oplist, opname, arg1, arg2, arg3)
local op = oplist[opname]
local type, value, err
if traits.is_function(op) then
-- op is a function, get the results by running it
type, value, err = op(self, arg1, arg2, arg3)
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, attr)
if not type and not err then -- no resulting type, but no error, thus generate one
err = stringer.pformat("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, rtype, lattr, rattr)
if not type and not err then -- no resulting type, but no error, thus generate one
err = stringer.pformat("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)
if self == type then
-- the type itself
return self
elseif type.is_any then
-- anything can be converted to and from `any`
return self
else
return false, stringer.pformat("no viable type conversion from `%s` to `%s`", type, self)
end
end
-- Get the desired type when converting this type from an attr.
function Type:get_convertible_from_attr(attr, explicit)
return self:get_convertible_from_type(attr.type, explicit)
end
-- Checks if this type is convertible from another type.
function Type:is_convertible_from_type(type, explicit, ...)
local ok, err = self:get_convertible_from_type(type, explicit, ...)
return not not ok, err
end
-- Checks if this type is convertible from an attr.
function Type:is_convertible_from_attr(attr, explicit, ...)
local ok, err = self:get_convertible_from_attr(attr, explicit, ...)
return not not ok, err
end
-- Checks if this type is convertible from a node, type or attr.
function Type:is_convertible_from(what, explicit, ...)
if traits.is_astnode(what) then
return self:is_convertible_from_attr(what.attr, explicit, ...)
elseif traits.is_type(what) then
return self:is_convertible_from_type(what, explicit, ...)
else --luacov:disable
assert(traits.is_attr(what))
return self:is_convertible_from_attr(what, explicit, ...)
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)
if self == type then
return self
end
return 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 and self == attr.type and attr.comptime
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.id == self.id
end
-- Give the underlying type when implicit dereferencing this type.
function Type:implict_deref_type()
return self
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
function Type.has_destroyable() return false end
function Type.has_copyable() return false end
function Type.has_varargs() 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 type(t1) == 'table' and type(t2) == 'table' and t1._type and t2._type then
if t1.id == t2.id then -- early check for same type (optimization)
-- types with the same type id should always be the same
return true
end
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, stringer.pformat('cannot reference not addressable type "%s"', ltype)
end
else
return nil, nil, stringer.pformat('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.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)
typelist[i] = nodes[i].attr.value
end
return typelist
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
-- 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
--------------------------------------------------------------------------------
-- 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.nodecl = 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 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_unpointable = true
function NiltypeType:_init(name)
Type._init(self, name, 0)
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_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
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_nilable = true
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
--------------------------------------------------------------------------------
-- 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_varargs = true
VaranysType.is_nolvalue = true
function VaranysType:_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(AnyType)
types.CVarargsType = CVarargsType
CVarargsType.is_cvarargs = true
CVarargsType.is_varargs = true
CVarargsType.is_nolvalue = true
function CVarargsType:_init(name, size)
Type._init(self, name, size)
end
--------------------------------------------------------------------------------
-- Arithmetic Type
--
-- The arithmetic type is used as a base type for creating the Integral and Float types.
-- Arithmetic types can perform arithmetic operations
-- like addition, subtraction, multiplication, division, etc.
local ArithmeticType = types.typeclass()
types.ArithmeticType = ArithmeticType
ArithmeticType.is_arithmetic = true
ArithmeticType.get_convertible_from_type = Type.get_convertible_from_type
function ArithmeticType:_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 ArithmeticType:is_initializable_from_attr(attr)
if attr and attr.comptime and attr.untyped and attr.type and attr.type.is_arithmetic then
-- initializing from an untyped compile time arithmetic is always possible
return true
end
return Type.is_initializable_from_attr(self, attr)
end
-- Negation operator for arithmetic types.
ArithmeticType.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 arithmetic types.
ArithmeticType.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_arithmetic 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 arithmetic type.
local function make_arith_cmpop(cmpfunc)
return function(ltype, rtype, lattr, rattr)
if rtype.is_arithmetic 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 arithmetic comparison operations.
ArithmeticType.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)
ArithmeticType.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)
ArithmeticType.binary_operators.lt = make_arith_cmpop(function(a,b,same)
if same then
return false
elseif a and b then
return a < b
end
end)
ArithmeticType.binary_operators.gt = make_arith_cmpop(function(a,b,same)
if same then
return false
elseif a and b then
return a > b
end
end)
--------------------------------------------------------------------------------
-- Integral Type
--
-- Integral type is used for unsigned and signed integer (whole numbers) types,
-- e.g. 'int64', 'uint64', ...
-- They have min and max values and cannot be fractional.
local IntegralType = types.typeclass(ArithmeticType)
types.IntegralType = IntegralType
IntegralType.is_integral = true
IntegralType.shape = shaper.fork_shape(Type.shape, {
-- Minimum and maximum value that the integral type can store.
min = shaper.arithmetic, max = shaper.arithmetic,
-- Signess of the integral type.
is_signed = shaper.optional_boolean, is_unsigned = shaper.optional_boolean,
})
function IntegralType:_init(name, size, is_unsigned)
ArithmeticType._init(self, name, size)
-- compute the min and max values
if is_unsigned then
self.min = bn.zero()
self.max = (bn.one() << self.bitsize) - 1
self.is_unsigned = true
else -- signed
self.min = -(bn.one() << self.bitsize) // 2
self.max = ((bn.one() << self.bitsize) // 2) - 1
self.is_signed = true
end
self['is_'..self.name] = true
end
-- Return unsigned integral version of this type.
function IntegralType:unsigned_type()
if self.is_unsigned then return self end
return primtypes['uint'..self.bitsize]
end
-- Return signed integral version of this type.
function IntegralType:signed_type()
if self.is_signed then return self end
return primtypes['int'..self.bitsize]
end
-- Get the desired type when converting this type from an attr.
function IntegralType:get_convertible_from_attr(attr, explicit)
if not explicit and attr.comptime and attr.type.is_arithmetic then
-- implicit conversion between two compile time arithmetic types,
-- we can convert only if the compiler time value does not overflow/underflow the type
local value = attr.value
if not traits.is_integral(value) then -- the value must be and integral
return false, stringer.pformat(
"constant value `%s` is fractional which is invalid for the type '%s'",
value, self)
elseif not self:is_inrange(value) then -- the value must be in our range
return false, stringer.pformat(
"constant value `%s` for type `%s` is out of range, the minimum is `%s` and maximum is `%s`",
value, self, self.min, self.max)
else
-- in range and integral, thus a valid conversion
return self
end
end
return ArithmeticType.get_convertible_from_attr(self, attr, explicit)
end
-- Get the desired type when converting this type from another type.
function IntegralType:get_convertible_from_type(type, explicit)
if type == self then -- early return for the same type
return self
elseif type.is_integral and self:is_type_inrange(type) then
-- implicit conversion from another integral that fits this integral
return self
elseif type.is_arithmetic then
-- implicit narrowing cast
return self
elseif explicit and type.is_pointer and self.size >= type.size then
-- explicit cast from a pointer to an integral that can fit the pointer
return self
end
return ArithmeticType.get_convertible_from_type(self, type, explicit)
end
-- Checks if this type arithmetic type can fit another arithmetic type.
-- To fit both min and max values of the other type must be in this type range.
function IntegralType:is_type_inrange(type)
if type.is_integral and self:is_inrange(type.min) and self:is_inrange(type.max) then
-- both min and max is in range
return true
end
return false
end
-- Wrap a compile time value to be fitted on this integral type.
-- Float values are truncated, integer value wraps around in case of overflow/underflow.
function IntegralType:wrap_value(value)
if traits.is_integral(value) then
-- wrap around in case the value is not in range
if not self:is_inrange(value) then
if self.is_signed and value > self.max then
-- special case for wrapping signed integers
value = -bn.bwrap(-value, self.bitsize)
else
value = bn.bwrap(value, self.bitsize)
end
end
else -- must be a float
value = bn.trunc(value)
end
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 IntegralType:promote_type_for_value(value)
if traits.is_integral(value) then
if self:is_inrange(value) then
-- this type already fits
return self
end
-- try to use a type of same signess until fit the size
local promotetypes
local fallbacktype
if self.is_unsigned and not bn.isneg(value) then -- preserve unsigned when possible
promotetypes = typedefs.promote_unsigned_types
fallbacktype = primtypes.uint64
else -- is signed
promotetypes = typedefs.promote_signed_types
fallbacktype = primtypes.int64
end
for i=1,#promotetypes do
local type = promotetypes[i]
if type.size >= self.size and type:is_inrange(value) then
-- both value and prev type fits
return type