Skip to content
← Back

src/semantic/dotnet/reflected_constants.ghul

1
@@IF.dotnet()
2
3
namespace Semantic.DotNet is
4
use TYPE = System.Type
5
6
use System.Reflection.FieldInfo
7
8
// What a reflected field turns out to be when asked for a constant
9
// value.
10
//
11
// A constant whose value is null is a case of its own rather than a
12
// reserved spelling inside the text: a constant string holds whatever
13
// a library author wrote, so no word is available to stand for
14
// something else.
15
union ReflectedConstant is
16
// Not a constant, or one whose value cannot be described as text
17
// - an ordinary field either way.
18
NONE
19
20
// A constant whose value is null, which is the only constant of a
21
// reference type metadata can hold.
22
ABSENT
23
24
VALUE(text: string) default
25
si
26
27
// Reads a reflected `const` field's value.
28
//
29
// A `const` is a compile-time literal: metadata carries the value and
30
// no field is emitted to hold it, because a language that inlines a
31
// constant at each use leaves nothing behind for anyone to load. So a
32
// consumer has to take the value from here rather than read the field
33
// it looks like.
34
//
35
// The value comes back as invariant-culture text, which is the form a
36
// reflected argument default is carried in too - `text_of` is what
37
// the two share, each deciding for itself what an absent value means.
38
class REFLECTED_CONSTANTS is
39
value_of(`field: FieldInfo) -> ReflectedConstant static is
40
if !`field.is_literal then
41
return ReflectedConstant.NONE
42
fi
43
44
let raw = `field.get_raw_constant_value()
45
46
if !raw? then
47
return ReflectedConstant.ABSENT
48
fi
49
50
if let text = text_of(raw, `field.field_type) then
51
return ReflectedConstant.VALUE(text)
52
fi
53
54
return ReflectedConstant.NONE
55
si
56
57
// A reflected value as invariant-culture text, or null when it is
58
// not one that can be described that way. Culture-independent
59
// because this is read back by the compiler rather than shown to
60
// anyone.
61
text_of(value: object, type: TYPE) -> string? static is
62
if
63
!type.is_primitive /\
64
!type.is_enum /\
65
type.full_name !~ "System.String"
66
then
67
return null
68
fi
69
70
let convertible = cast System.IConvertible?(value)
71
72
if !convertible? then
73
return null
74
fi
75
76
return convertible.to_string(
77
System.Globalization.CultureInfo.invariant_culture
78
)
79
si
80
si
81
si