file_name
stringlengths 5
52
| name
stringlengths 4
95
| original_source_type
stringlengths 0
23k
| source_type
stringlengths 9
23k
| source_definition
stringlengths 9
57.9k
| source
dict | source_range
dict | file_context
stringlengths 0
721k
| dependencies
dict | opens_and_abbrevs
listlengths 2
94
| vconfig
dict | interleaved
bool 1
class | verbose_type
stringlengths 1
7.42k
| effect
stringclasses 118
values | effect_flags
sequencelengths 0
2
| mutual_with
sequencelengths 0
11
| ideal_premises
sequencelengths 0
236
| proof_features
sequencelengths 0
1
| is_simple_lemma
bool 2
classes | is_div
bool 2
classes | is_proof
bool 2
classes | is_simply_typed
bool 2
classes | is_type
bool 2
classes | partial_definition
stringlengths 5
3.99k
| completed_definiton
stringlengths 1
1.63M
| isa_cross_project_example
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Hacl.Bignum25519.fst | Hacl.Bignum25519.reduce_513 | val reduce_513:
a:felem ->
Stack unit
(requires fun h -> live h a /\
F51.felem_fits h a (9, 10, 9, 9, 9)
)
(ensures fun h0 _ h1 -> modifies (loc a) h0 h1 /\
F51.fevalh h1 a == F51.fevalh h0 a /\
F51.mul_inv_t h1 a
) | val reduce_513:
a:felem ->
Stack unit
(requires fun h -> live h a /\
F51.felem_fits h a (9, 10, 9, 9, 9)
)
(ensures fun h0 _ h1 -> modifies (loc a) h0 h1 /\
F51.fevalh h1 a == F51.fevalh h0 a /\
F51.mul_inv_t h1 a
) | let reduce_513 a =
let (f0, f1, f2, f3, f4) = (a.(0ul), a.(1ul), a.(2ul), a.(3ul), a.(4ul)) in
let tmp0, c0 = carry51 #9 f0 (u64 0) in
let tmp1, c1 = carry51 #10 f1 c0 in
let tmp2, c2 = carry51 #9 f2 c1 in
let tmp3, c3 = carry51 #9 f3 c2 in
let tmp4, c4 = carry51 #9 f4 c3 in
assert (S51.felem_fits5 (tmp0, tmp1, tmp2, tmp3, tmp4) (1, 1, 1, 1, 1));
SL51.lemma_carry5_simplify c0 c1 c2 c3 c4 tmp0 tmp1 tmp2 tmp3 tmp4;
assert (
S51.as_nat5 (f0, f1, f2, f3, f4) % SC.prime ==
(S51.as_nat5 (tmp0, tmp1, tmp2, tmp3, tmp4) + v c4 * 19) % SC.prime);
[@inline_let]
let tmp0', c5 = carry51 #1 tmp0 (c4 *! u64 19) in
[@inline_let]
let tmp1' = tmp1 +! c5 in
Hacl.Spec.Curve25519.Field51.lemma_mul_inv (tmp0', tmp1, tmp2, tmp3, tmp4) c5;
make_u64_5 a tmp0' tmp1' tmp2 tmp3 tmp4 | {
"file_name": "code/ed25519/Hacl.Bignum25519.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 41,
"end_line": 114,
"start_col": 0,
"start_line": 95
} | module Hacl.Bignum25519
module ST = FStar.HyperStack.ST
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.ByteBuffer
module LSeq = Lib.Sequence
module BSeq = Lib.ByteSequence
module S51 = Hacl.Spec.Curve25519.Field51.Definition
module SL51 = Hacl.Spec.Curve25519.Field51.Lemmas
module BN = Hacl.Impl.Curve25519.Field51
module SC = Spec.Curve25519
friend Hacl.Curve25519_51
#reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0"
inline_for_extraction noextract
let mask_51 = u64 0x7ffffffffffff
let make_u64_5 b s0 s1 s2 s3 s4 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4
let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9
let make_zero b =
b.(0ul) <- u64 0;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 0, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 0)
let make_one b =
b.(0ul) <- u64 1;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 1, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 1)
[@CInline]
let fsum out a b =
BN.fadd out a b
[@CInline]
let fdifference out a b =
BN.fsub out a b
inline_for_extraction noextract
val carry51:
#m:S51.scale64{m < 8192}
-> l:uint64
-> cin:uint64 ->
Pure (uint64 & uint64)
(requires
S51.felem_fits1 l m /\
S51.felem_fits1 cin 1)
(ensures fun (l0, l1) ->
v l + v cin == v l1 * pow2 51 + v l0 /\
S51.felem_fits1 l0 1 /\ uint_v l1 < m + 1)
let carry51 l cin =
let l' = l +! cin in
mod_mask_lemma l' 51ul;
assert (v (mod_mask #U64 #SEC 51ul) == v mask_51);
FStar.Math.Lemmas.pow2_modulo_modulo_lemma_1 (v l') 51 64;
FStar.Math.Lemmas.euclidean_division_definition (v l') (pow2 51);
FStar.Math.Lemmas.pow2_minus 64 51;
(l' &. mask_51, l' >>. 51ul) | {
"checked_file": "/",
"dependencies": [
"Spec.Ed25519.fst.checked",
"Spec.Curve25519.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"Lib.ByteBuffer.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Definition.fst.checked",
"Hacl.Spec.Curve25519.Field51.fst.checked",
"Hacl.Impl.Curve25519.Field51.fst.checked",
"Hacl.Curve25519_51.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Hacl.Bignum25519.fst"
} | [
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Curve25519.Field51",
"short_module": "BN"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Lemmas",
"short_module": "SL51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Ed25519.Field51",
"short_module": "F51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | a: Hacl.Bignum25519.felem -> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Hacl.Bignum25519.felem",
"Lib.IntTypes.uint64",
"Hacl.Bignum25519.make_u64_5",
"Prims.unit",
"Hacl.Spec.Curve25519.Field51.lemma_mul_inv",
"FStar.Pervasives.Native.Mktuple5",
"Lib.IntTypes.int_t",
"Lib.IntTypes.U64",
"Lib.IntTypes.SEC",
"Lib.IntTypes.op_Plus_Bang",
"FStar.Pervasives.Native.tuple2",
"Hacl.Bignum25519.carry51",
"Lib.IntTypes.op_Star_Bang",
"Lib.IntTypes.u64",
"Prims._assert",
"Prims.eq2",
"Prims.int",
"Prims.op_Modulus",
"Hacl.Spec.Curve25519.Field51.Definition.as_nat5",
"Spec.Curve25519.prime",
"Prims.op_Addition",
"FStar.Mul.op_Star",
"Lib.IntTypes.v",
"Hacl.Spec.Curve25519.Field51.Lemmas.lemma_carry5_simplify",
"Hacl.Spec.Curve25519.Field51.Definition.felem_fits5",
"Prims.nat",
"FStar.Pervasives.Native.tuple5",
"Lib.Buffer.op_Array_Access",
"Lib.Buffer.MUT",
"FStar.UInt32.__uint_to_t"
] | [] | false | true | false | false | false | let reduce_513 a =
| let f0, f1, f2, f3, f4 = (a.(0ul), a.(1ul), a.(2ul), a.(3ul), a.(4ul)) in
let tmp0, c0 = carry51 #9 f0 (u64 0) in
let tmp1, c1 = carry51 #10 f1 c0 in
let tmp2, c2 = carry51 #9 f2 c1 in
let tmp3, c3 = carry51 #9 f3 c2 in
let tmp4, c4 = carry51 #9 f4 c3 in
assert (S51.felem_fits5 (tmp0, tmp1, tmp2, tmp3, tmp4) (1, 1, 1, 1, 1));
SL51.lemma_carry5_simplify c0 c1 c2 c3 c4 tmp0 tmp1 tmp2 tmp3 tmp4;
assert (S51.as_nat5 (f0, f1, f2, f3, f4) % SC.prime ==
(S51.as_nat5 (tmp0, tmp1, tmp2, tmp3, tmp4) + v c4 * 19) % SC.prime);
[@@ inline_let ]let tmp0', c5 = carry51 #1 tmp0 (c4 *! u64 19) in
[@@ inline_let ]let tmp1' = tmp1 +! c5 in
Hacl.Spec.Curve25519.Field51.lemma_mul_inv (tmp0', tmp1, tmp2, tmp3, tmp4) c5;
make_u64_5 a tmp0' tmp1' tmp2 tmp3 tmp4 | false |
Hacl.Bignum25519.fst | Hacl.Bignum25519.inverse | val inverse:
out:felem
-> a:felem ->
Stack unit
(requires fun h -> live h out /\ live h a /\ disjoint a out /\
F51.felem_fits h a (1, 2, 1, 1, 1)
)
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.felem_fits h1 out (1, 2, 1, 1, 1) /\
F51.fevalh h1 out == SC.fpow (F51.fevalh h0 a) (SC.prime - 2)
) | val inverse:
out:felem
-> a:felem ->
Stack unit
(requires fun h -> live h out /\ live h a /\ disjoint a out /\
F51.felem_fits h a (1, 2, 1, 1, 1)
)
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.felem_fits h1 out (1, 2, 1, 1, 1) /\
F51.fevalh h1 out == SC.fpow (F51.fevalh h0 a) (SC.prime - 2)
) | let inverse out a =
push_frame();
let tmp = create 10ul (u128 0) in
Hacl.Curve25519_51.finv out a tmp;
pop_frame() | {
"file_name": "code/ed25519/Hacl.Bignum25519.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 13,
"end_line": 239,
"start_col": 0,
"start_line": 235
} | module Hacl.Bignum25519
module ST = FStar.HyperStack.ST
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.ByteBuffer
module LSeq = Lib.Sequence
module BSeq = Lib.ByteSequence
module S51 = Hacl.Spec.Curve25519.Field51.Definition
module SL51 = Hacl.Spec.Curve25519.Field51.Lemmas
module BN = Hacl.Impl.Curve25519.Field51
module SC = Spec.Curve25519
friend Hacl.Curve25519_51
#reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0"
inline_for_extraction noextract
let mask_51 = u64 0x7ffffffffffff
let make_u64_5 b s0 s1 s2 s3 s4 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4
let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9
let make_zero b =
b.(0ul) <- u64 0;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 0, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 0)
let make_one b =
b.(0ul) <- u64 1;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 1, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 1)
[@CInline]
let fsum out a b =
BN.fadd out a b
[@CInline]
let fdifference out a b =
BN.fsub out a b
inline_for_extraction noextract
val carry51:
#m:S51.scale64{m < 8192}
-> l:uint64
-> cin:uint64 ->
Pure (uint64 & uint64)
(requires
S51.felem_fits1 l m /\
S51.felem_fits1 cin 1)
(ensures fun (l0, l1) ->
v l + v cin == v l1 * pow2 51 + v l0 /\
S51.felem_fits1 l0 1 /\ uint_v l1 < m + 1)
let carry51 l cin =
let l' = l +! cin in
mod_mask_lemma l' 51ul;
assert (v (mod_mask #U64 #SEC 51ul) == v mask_51);
FStar.Math.Lemmas.pow2_modulo_modulo_lemma_1 (v l') 51 64;
FStar.Math.Lemmas.euclidean_division_definition (v l') (pow2 51);
FStar.Math.Lemmas.pow2_minus 64 51;
(l' &. mask_51, l' >>. 51ul)
let reduce_513 a =
let (f0, f1, f2, f3, f4) = (a.(0ul), a.(1ul), a.(2ul), a.(3ul), a.(4ul)) in
let tmp0, c0 = carry51 #9 f0 (u64 0) in
let tmp1, c1 = carry51 #10 f1 c0 in
let tmp2, c2 = carry51 #9 f2 c1 in
let tmp3, c3 = carry51 #9 f3 c2 in
let tmp4, c4 = carry51 #9 f4 c3 in
assert (S51.felem_fits5 (tmp0, tmp1, tmp2, tmp3, tmp4) (1, 1, 1, 1, 1));
SL51.lemma_carry5_simplify c0 c1 c2 c3 c4 tmp0 tmp1 tmp2 tmp3 tmp4;
assert (
S51.as_nat5 (f0, f1, f2, f3, f4) % SC.prime ==
(S51.as_nat5 (tmp0, tmp1, tmp2, tmp3, tmp4) + v c4 * 19) % SC.prime);
[@inline_let]
let tmp0', c5 = carry51 #1 tmp0 (c4 *! u64 19) in
[@inline_let]
let tmp1' = tmp1 +! c5 in
Hacl.Spec.Curve25519.Field51.lemma_mul_inv (tmp0', tmp1, tmp2, tmp3, tmp4) c5;
make_u64_5 a tmp0' tmp1' tmp2 tmp3 tmp4
[@CInline]
let fmul output input input2 =
push_frame();
let tmp = create 10ul (u128 0) in
BN.fmul output input input2 tmp;
pop_frame()
[@CInline]
let times_2 out a =
(**) let h0 = ST.get() in
let a0 = a.(0ul) in
let a1 = a.(1ul) in
let a2 = a.(2ul) in
let a3 = a.(3ul) in
let a4 = a.(4ul) in
let o0 = u64 2 *. a0 in
let o1 = u64 2 *. a1 in
let o2 = u64 2 *. a2 in
let o3 = u64 2 *. a3 in
let o4 = u64 2 *. a4 in
make_u64_5 out o0 o1 o2 o3 o4;
(**) let h1 = ST.get() in
(**) assert (S51.felem_fits1 a0 1);
(**) assert (F51.felem_fits h1 out (2, 4, 2, 2, 2));
calc (==) {
(2 * (F51.fevalh h0 a)) % SC.prime;
(==) { calc (==) {
F51.fevalh h0 a;
(==) { }
S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime;
}
}
(2 * (S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime)) % SC.prime;
(==) { FStar.Math.Lemmas.lemma_mod_mul_distr_r 2 (S51.as_nat5 (a0, a1, a2, a3, a4)) SC.prime }
(2 * S51.as_nat5 (a0, a1, a2, a3, a4)) % SC.prime;
(==) { calc (==) {
2 * S51.as_nat5 (a0, a1, a2, a3, a4);
(==) { SL51.lemma_smul_felem5 (u64 2) (a0, a1, a2, a3, a4) }
2 * v a0 + 2 * v a1 * S51.pow51 + 2 * v a2 * S51.pow51 * S51.pow51 +
2 * v a3 * S51.pow51 * S51.pow51 * S51.pow51 +
2 * v a4 * S51.pow51 * S51.pow51 * S51.pow51 * S51.pow51;
(==) {
assert_norm (2 * S51.pow51 < pow2 64);
assert_norm (4 * S51.pow51 < pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a0) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a1) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a2) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a3) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a4) (pow2 64)
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4);
}
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4) % SC.prime;
(==) { }
F51.fevalh h1 out;
}
[@CInline]
let times_d out a =
push_frame();
let d = create 5ul (u64 0) in
d.(0ul) <- u64 0x00034dca135978a3;
d.(1ul) <- u64 0x0001a8283b156ebd;
d.(2ul) <- u64 0x0005e7a26001c029;
d.(3ul) <- u64 0x000739c663a03cbb;
d.(4ul) <- u64 0x00052036cee2b6ff;
assert_norm (S51.as_nat5 (u64 0x00034dca135978a3, u64 0x0001a8283b156ebd,
u64 0x0005e7a26001c029, u64 0x000739c663a03cbb, u64 0x00052036cee2b6ff) %
Spec.Curve25519.prime == Spec.Ed25519.d);
fmul out d a;
pop_frame()
[@CInline]
let times_2d out a =
push_frame();
let d2 = create 5ul (u64 0) in
d2.(0ul) <- u64 0x00069b9426b2f159;
d2.(1ul) <- u64 0x00035050762add7a;
d2.(2ul) <- u64 0x0003cf44c0038052;
d2.(3ul) <- u64 0x0006738cc7407977;
d2.(4ul) <- u64 0x0002406d9dc56dff;
fmul out d2 a;
assert_norm (S51.as_nat5 (u64 0x00069b9426b2f159, u64 0x00035050762add7a,
u64 0x0003cf44c0038052, u64 0x0006738cc7407977, u64 0x0002406d9dc56dff) %
Spec.Curve25519.prime == 2 `SC.fmul` Spec.Ed25519.d);
pop_frame()
[@CInline]
let fsquare out a =
push_frame();
let tmp = create 5ul (u128 0) in
BN.fsqr out a tmp;
pop_frame()
[@CInline]
let fsquare_times output input count =
push_frame();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output input tmp count;
pop_frame()
[@CInline]
let fsquare_times_inplace output count =
push_frame();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output output tmp count;
pop_frame() | {
"checked_file": "/",
"dependencies": [
"Spec.Ed25519.fst.checked",
"Spec.Curve25519.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"Lib.ByteBuffer.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Definition.fst.checked",
"Hacl.Spec.Curve25519.Field51.fst.checked",
"Hacl.Impl.Curve25519.Field51.fst.checked",
"Hacl.Curve25519_51.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Hacl.Bignum25519.fst"
} | [
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Curve25519.Field51",
"short_module": "BN"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Lemmas",
"short_module": "SL51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Ed25519.Field51",
"short_module": "F51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | out: Hacl.Bignum25519.felem -> a: Hacl.Bignum25519.felem -> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Hacl.Bignum25519.felem",
"FStar.HyperStack.ST.pop_frame",
"Prims.unit",
"Hacl.Curve25519_51.finv",
"Lib.Buffer.lbuffer_t",
"Lib.Buffer.MUT",
"Lib.IntTypes.int_t",
"Lib.IntTypes.U128",
"Lib.IntTypes.SEC",
"FStar.UInt32.uint_to_t",
"FStar.UInt32.t",
"Lib.Buffer.create",
"Hacl.Impl.Curve25519.Fields.Core.wide",
"Hacl.Impl.Curve25519.Fields.Core.M51",
"FStar.UInt32.__uint_to_t",
"Lib.IntTypes.u128",
"Lib.Buffer.lbuffer",
"FStar.HyperStack.ST.push_frame"
] | [] | false | true | false | false | false | let inverse out a =
| push_frame ();
let tmp = create 10ul (u128 0) in
Hacl.Curve25519_51.finv out a tmp;
pop_frame () | false |
Hacl.Bignum25519.fst | Hacl.Bignum25519.fsquare_times_inplace | val fsquare_times_inplace:
out:felem
-> n:size_t{v n > 0} ->
Stack unit
(requires fun h -> live h out /\ F51.felem_fits h out (1, 2, 1, 1, 1))
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.felem_fits h1 out (1, 2, 1, 1, 1) /\
F51.fevalh h1 out == Hacl.Spec.Curve25519.Finv.pow (F51.fevalh h0 out) (pow2 (v n))
) | val fsquare_times_inplace:
out:felem
-> n:size_t{v n > 0} ->
Stack unit
(requires fun h -> live h out /\ F51.felem_fits h out (1, 2, 1, 1, 1))
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.felem_fits h1 out (1, 2, 1, 1, 1) /\
F51.fevalh h1 out == Hacl.Spec.Curve25519.Finv.pow (F51.fevalh h0 out) (pow2 (v n))
) | let fsquare_times_inplace output count =
push_frame();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output output tmp count;
pop_frame() | {
"file_name": "code/ed25519/Hacl.Bignum25519.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 13,
"end_line": 232,
"start_col": 0,
"start_line": 228
} | module Hacl.Bignum25519
module ST = FStar.HyperStack.ST
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.ByteBuffer
module LSeq = Lib.Sequence
module BSeq = Lib.ByteSequence
module S51 = Hacl.Spec.Curve25519.Field51.Definition
module SL51 = Hacl.Spec.Curve25519.Field51.Lemmas
module BN = Hacl.Impl.Curve25519.Field51
module SC = Spec.Curve25519
friend Hacl.Curve25519_51
#reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0"
inline_for_extraction noextract
let mask_51 = u64 0x7ffffffffffff
let make_u64_5 b s0 s1 s2 s3 s4 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4
let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9
let make_zero b =
b.(0ul) <- u64 0;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 0, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 0)
let make_one b =
b.(0ul) <- u64 1;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 1, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 1)
[@CInline]
let fsum out a b =
BN.fadd out a b
[@CInline]
let fdifference out a b =
BN.fsub out a b
inline_for_extraction noextract
val carry51:
#m:S51.scale64{m < 8192}
-> l:uint64
-> cin:uint64 ->
Pure (uint64 & uint64)
(requires
S51.felem_fits1 l m /\
S51.felem_fits1 cin 1)
(ensures fun (l0, l1) ->
v l + v cin == v l1 * pow2 51 + v l0 /\
S51.felem_fits1 l0 1 /\ uint_v l1 < m + 1)
let carry51 l cin =
let l' = l +! cin in
mod_mask_lemma l' 51ul;
assert (v (mod_mask #U64 #SEC 51ul) == v mask_51);
FStar.Math.Lemmas.pow2_modulo_modulo_lemma_1 (v l') 51 64;
FStar.Math.Lemmas.euclidean_division_definition (v l') (pow2 51);
FStar.Math.Lemmas.pow2_minus 64 51;
(l' &. mask_51, l' >>. 51ul)
let reduce_513 a =
let (f0, f1, f2, f3, f4) = (a.(0ul), a.(1ul), a.(2ul), a.(3ul), a.(4ul)) in
let tmp0, c0 = carry51 #9 f0 (u64 0) in
let tmp1, c1 = carry51 #10 f1 c0 in
let tmp2, c2 = carry51 #9 f2 c1 in
let tmp3, c3 = carry51 #9 f3 c2 in
let tmp4, c4 = carry51 #9 f4 c3 in
assert (S51.felem_fits5 (tmp0, tmp1, tmp2, tmp3, tmp4) (1, 1, 1, 1, 1));
SL51.lemma_carry5_simplify c0 c1 c2 c3 c4 tmp0 tmp1 tmp2 tmp3 tmp4;
assert (
S51.as_nat5 (f0, f1, f2, f3, f4) % SC.prime ==
(S51.as_nat5 (tmp0, tmp1, tmp2, tmp3, tmp4) + v c4 * 19) % SC.prime);
[@inline_let]
let tmp0', c5 = carry51 #1 tmp0 (c4 *! u64 19) in
[@inline_let]
let tmp1' = tmp1 +! c5 in
Hacl.Spec.Curve25519.Field51.lemma_mul_inv (tmp0', tmp1, tmp2, tmp3, tmp4) c5;
make_u64_5 a tmp0' tmp1' tmp2 tmp3 tmp4
[@CInline]
let fmul output input input2 =
push_frame();
let tmp = create 10ul (u128 0) in
BN.fmul output input input2 tmp;
pop_frame()
[@CInline]
let times_2 out a =
(**) let h0 = ST.get() in
let a0 = a.(0ul) in
let a1 = a.(1ul) in
let a2 = a.(2ul) in
let a3 = a.(3ul) in
let a4 = a.(4ul) in
let o0 = u64 2 *. a0 in
let o1 = u64 2 *. a1 in
let o2 = u64 2 *. a2 in
let o3 = u64 2 *. a3 in
let o4 = u64 2 *. a4 in
make_u64_5 out o0 o1 o2 o3 o4;
(**) let h1 = ST.get() in
(**) assert (S51.felem_fits1 a0 1);
(**) assert (F51.felem_fits h1 out (2, 4, 2, 2, 2));
calc (==) {
(2 * (F51.fevalh h0 a)) % SC.prime;
(==) { calc (==) {
F51.fevalh h0 a;
(==) { }
S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime;
}
}
(2 * (S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime)) % SC.prime;
(==) { FStar.Math.Lemmas.lemma_mod_mul_distr_r 2 (S51.as_nat5 (a0, a1, a2, a3, a4)) SC.prime }
(2 * S51.as_nat5 (a0, a1, a2, a3, a4)) % SC.prime;
(==) { calc (==) {
2 * S51.as_nat5 (a0, a1, a2, a3, a4);
(==) { SL51.lemma_smul_felem5 (u64 2) (a0, a1, a2, a3, a4) }
2 * v a0 + 2 * v a1 * S51.pow51 + 2 * v a2 * S51.pow51 * S51.pow51 +
2 * v a3 * S51.pow51 * S51.pow51 * S51.pow51 +
2 * v a4 * S51.pow51 * S51.pow51 * S51.pow51 * S51.pow51;
(==) {
assert_norm (2 * S51.pow51 < pow2 64);
assert_norm (4 * S51.pow51 < pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a0) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a1) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a2) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a3) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a4) (pow2 64)
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4);
}
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4) % SC.prime;
(==) { }
F51.fevalh h1 out;
}
[@CInline]
let times_d out a =
push_frame();
let d = create 5ul (u64 0) in
d.(0ul) <- u64 0x00034dca135978a3;
d.(1ul) <- u64 0x0001a8283b156ebd;
d.(2ul) <- u64 0x0005e7a26001c029;
d.(3ul) <- u64 0x000739c663a03cbb;
d.(4ul) <- u64 0x00052036cee2b6ff;
assert_norm (S51.as_nat5 (u64 0x00034dca135978a3, u64 0x0001a8283b156ebd,
u64 0x0005e7a26001c029, u64 0x000739c663a03cbb, u64 0x00052036cee2b6ff) %
Spec.Curve25519.prime == Spec.Ed25519.d);
fmul out d a;
pop_frame()
[@CInline]
let times_2d out a =
push_frame();
let d2 = create 5ul (u64 0) in
d2.(0ul) <- u64 0x00069b9426b2f159;
d2.(1ul) <- u64 0x00035050762add7a;
d2.(2ul) <- u64 0x0003cf44c0038052;
d2.(3ul) <- u64 0x0006738cc7407977;
d2.(4ul) <- u64 0x0002406d9dc56dff;
fmul out d2 a;
assert_norm (S51.as_nat5 (u64 0x00069b9426b2f159, u64 0x00035050762add7a,
u64 0x0003cf44c0038052, u64 0x0006738cc7407977, u64 0x0002406d9dc56dff) %
Spec.Curve25519.prime == 2 `SC.fmul` Spec.Ed25519.d);
pop_frame()
[@CInline]
let fsquare out a =
push_frame();
let tmp = create 5ul (u128 0) in
BN.fsqr out a tmp;
pop_frame()
[@CInline]
let fsquare_times output input count =
push_frame();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output input tmp count;
pop_frame() | {
"checked_file": "/",
"dependencies": [
"Spec.Ed25519.fst.checked",
"Spec.Curve25519.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"Lib.ByteBuffer.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Definition.fst.checked",
"Hacl.Spec.Curve25519.Field51.fst.checked",
"Hacl.Impl.Curve25519.Field51.fst.checked",
"Hacl.Curve25519_51.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Hacl.Bignum25519.fst"
} | [
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Curve25519.Field51",
"short_module": "BN"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Lemmas",
"short_module": "SL51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Ed25519.Field51",
"short_module": "F51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | out: Hacl.Bignum25519.felem -> n: Lib.IntTypes.size_t{Lib.IntTypes.v n > 0}
-> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Hacl.Bignum25519.felem",
"Lib.IntTypes.size_t",
"Prims.b2t",
"Prims.op_GreaterThan",
"Lib.IntTypes.v",
"Lib.IntTypes.U32",
"Lib.IntTypes.PUB",
"FStar.HyperStack.ST.pop_frame",
"Prims.unit",
"Hacl.Curve25519_51.fsquare_times",
"Lib.Buffer.lbuffer_t",
"Lib.Buffer.MUT",
"Lib.IntTypes.int_t",
"Lib.IntTypes.U128",
"Lib.IntTypes.SEC",
"FStar.UInt32.uint_to_t",
"FStar.UInt32.t",
"Lib.Buffer.create",
"Hacl.Impl.Curve25519.Fields.Core.wide",
"Hacl.Impl.Curve25519.Fields.Core.M51",
"FStar.UInt32.__uint_to_t",
"Lib.IntTypes.u128",
"Lib.Buffer.lbuffer",
"FStar.HyperStack.ST.push_frame"
] | [] | false | true | false | false | false | let fsquare_times_inplace output count =
| push_frame ();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output output tmp count;
pop_frame () | false |
Hacl.Bignum25519.fst | Hacl.Bignum25519.fmul | val fmul:
out:felem
-> a:felem
-> b:felem ->
Stack unit
(requires fun h -> live h out /\ live h a /\ live h b /\
F51.felem_fits h a (9, 10, 9, 9, 9) /\
F51.felem_fits h b (9, 10, 9, 9, 9)
)
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.mul_inv_t h1 out /\
F51.fevalh h1 out == SC.fmul (F51.fevalh h0 a) (F51.fevalh h0 b)
) | val fmul:
out:felem
-> a:felem
-> b:felem ->
Stack unit
(requires fun h -> live h out /\ live h a /\ live h b /\
F51.felem_fits h a (9, 10, 9, 9, 9) /\
F51.felem_fits h b (9, 10, 9, 9, 9)
)
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.mul_inv_t h1 out /\
F51.fevalh h1 out == SC.fmul (F51.fevalh h0 a) (F51.fevalh h0 b)
) | let fmul output input input2 =
push_frame();
let tmp = create 10ul (u128 0) in
BN.fmul output input input2 tmp;
pop_frame() | {
"file_name": "code/ed25519/Hacl.Bignum25519.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 13,
"end_line": 122,
"start_col": 0,
"start_line": 118
} | module Hacl.Bignum25519
module ST = FStar.HyperStack.ST
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.ByteBuffer
module LSeq = Lib.Sequence
module BSeq = Lib.ByteSequence
module S51 = Hacl.Spec.Curve25519.Field51.Definition
module SL51 = Hacl.Spec.Curve25519.Field51.Lemmas
module BN = Hacl.Impl.Curve25519.Field51
module SC = Spec.Curve25519
friend Hacl.Curve25519_51
#reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0"
inline_for_extraction noextract
let mask_51 = u64 0x7ffffffffffff
let make_u64_5 b s0 s1 s2 s3 s4 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4
let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9
let make_zero b =
b.(0ul) <- u64 0;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 0, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 0)
let make_one b =
b.(0ul) <- u64 1;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 1, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 1)
[@CInline]
let fsum out a b =
BN.fadd out a b
[@CInline]
let fdifference out a b =
BN.fsub out a b
inline_for_extraction noextract
val carry51:
#m:S51.scale64{m < 8192}
-> l:uint64
-> cin:uint64 ->
Pure (uint64 & uint64)
(requires
S51.felem_fits1 l m /\
S51.felem_fits1 cin 1)
(ensures fun (l0, l1) ->
v l + v cin == v l1 * pow2 51 + v l0 /\
S51.felem_fits1 l0 1 /\ uint_v l1 < m + 1)
let carry51 l cin =
let l' = l +! cin in
mod_mask_lemma l' 51ul;
assert (v (mod_mask #U64 #SEC 51ul) == v mask_51);
FStar.Math.Lemmas.pow2_modulo_modulo_lemma_1 (v l') 51 64;
FStar.Math.Lemmas.euclidean_division_definition (v l') (pow2 51);
FStar.Math.Lemmas.pow2_minus 64 51;
(l' &. mask_51, l' >>. 51ul)
let reduce_513 a =
let (f0, f1, f2, f3, f4) = (a.(0ul), a.(1ul), a.(2ul), a.(3ul), a.(4ul)) in
let tmp0, c0 = carry51 #9 f0 (u64 0) in
let tmp1, c1 = carry51 #10 f1 c0 in
let tmp2, c2 = carry51 #9 f2 c1 in
let tmp3, c3 = carry51 #9 f3 c2 in
let tmp4, c4 = carry51 #9 f4 c3 in
assert (S51.felem_fits5 (tmp0, tmp1, tmp2, tmp3, tmp4) (1, 1, 1, 1, 1));
SL51.lemma_carry5_simplify c0 c1 c2 c3 c4 tmp0 tmp1 tmp2 tmp3 tmp4;
assert (
S51.as_nat5 (f0, f1, f2, f3, f4) % SC.prime ==
(S51.as_nat5 (tmp0, tmp1, tmp2, tmp3, tmp4) + v c4 * 19) % SC.prime);
[@inline_let]
let tmp0', c5 = carry51 #1 tmp0 (c4 *! u64 19) in
[@inline_let]
let tmp1' = tmp1 +! c5 in
Hacl.Spec.Curve25519.Field51.lemma_mul_inv (tmp0', tmp1, tmp2, tmp3, tmp4) c5;
make_u64_5 a tmp0' tmp1' tmp2 tmp3 tmp4 | {
"checked_file": "/",
"dependencies": [
"Spec.Ed25519.fst.checked",
"Spec.Curve25519.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"Lib.ByteBuffer.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Definition.fst.checked",
"Hacl.Spec.Curve25519.Field51.fst.checked",
"Hacl.Impl.Curve25519.Field51.fst.checked",
"Hacl.Curve25519_51.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Hacl.Bignum25519.fst"
} | [
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Curve25519.Field51",
"short_module": "BN"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Lemmas",
"short_module": "SL51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Ed25519.Field51",
"short_module": "F51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | out: Hacl.Bignum25519.felem -> a: Hacl.Bignum25519.felem -> b: Hacl.Bignum25519.felem
-> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Hacl.Bignum25519.felem",
"FStar.HyperStack.ST.pop_frame",
"Prims.unit",
"Hacl.Impl.Curve25519.Field51.fmul",
"Lib.Buffer.lbuffer_t",
"Lib.Buffer.MUT",
"Lib.IntTypes.int_t",
"Lib.IntTypes.U128",
"Lib.IntTypes.SEC",
"FStar.UInt32.uint_to_t",
"FStar.UInt32.t",
"Lib.Buffer.create",
"Hacl.Impl.Curve25519.Fields.Core.wide",
"Hacl.Impl.Curve25519.Fields.Core.M51",
"FStar.UInt32.__uint_to_t",
"Lib.IntTypes.u128",
"Lib.Buffer.lbuffer",
"FStar.HyperStack.ST.push_frame"
] | [] | false | true | false | false | false | let fmul output input input2 =
| push_frame ();
let tmp = create 10ul (u128 0) in
BN.fmul output input input2 tmp;
pop_frame () | false |
Hacl.Bignum25519.fst | Hacl.Bignum25519.make_u64_10 | val make_u64_10:
b:lbuffer uint64 10ul
-> s0:uint64 -> s1:uint64 -> s2:uint64 -> s3:uint64 -> s4:uint64
-> s5:uint64 -> s6:uint64 -> s7:uint64 -> s8:uint64 -> s9:uint64 ->
Stack unit
(requires fun h -> live h b)
(ensures fun h0 _ h1 -> modifies (loc b) h0 h1 /\
(let s = as_seq h1 b in
Seq.index s 0 == s0 /\
Seq.index s 1 == s1 /\
Seq.index s 2 == s2 /\
Seq.index s 3 == s3 /\
Seq.index s 4 == s4 /\
Seq.index s 5 == s5 /\
Seq.index s 6 == s6 /\
Seq.index s 7 == s7 /\
Seq.index s 8 == s8 /\
Seq.index s 9 == s9)
) | val make_u64_10:
b:lbuffer uint64 10ul
-> s0:uint64 -> s1:uint64 -> s2:uint64 -> s3:uint64 -> s4:uint64
-> s5:uint64 -> s6:uint64 -> s7:uint64 -> s8:uint64 -> s9:uint64 ->
Stack unit
(requires fun h -> live h b)
(ensures fun h0 _ h1 -> modifies (loc b) h0 h1 /\
(let s = as_seq h1 b in
Seq.index s 0 == s0 /\
Seq.index s 1 == s1 /\
Seq.index s 2 == s2 /\
Seq.index s 3 == s3 /\
Seq.index s 4 == s4 /\
Seq.index s 5 == s5 /\
Seq.index s 6 == s6 /\
Seq.index s 7 == s7 /\
Seq.index s 8 == s8 /\
Seq.index s 9 == s9)
) | let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9 | {
"file_name": "code/ed25519/Hacl.Bignum25519.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 15,
"end_line": 43,
"start_col": 0,
"start_line": 33
} | module Hacl.Bignum25519
module ST = FStar.HyperStack.ST
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.ByteBuffer
module LSeq = Lib.Sequence
module BSeq = Lib.ByteSequence
module S51 = Hacl.Spec.Curve25519.Field51.Definition
module SL51 = Hacl.Spec.Curve25519.Field51.Lemmas
module BN = Hacl.Impl.Curve25519.Field51
module SC = Spec.Curve25519
friend Hacl.Curve25519_51
#reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0"
inline_for_extraction noextract
let mask_51 = u64 0x7ffffffffffff
let make_u64_5 b s0 s1 s2 s3 s4 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4 | {
"checked_file": "/",
"dependencies": [
"Spec.Ed25519.fst.checked",
"Spec.Curve25519.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"Lib.ByteBuffer.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Definition.fst.checked",
"Hacl.Spec.Curve25519.Field51.fst.checked",
"Hacl.Impl.Curve25519.Field51.fst.checked",
"Hacl.Curve25519_51.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Hacl.Bignum25519.fst"
} | [
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Curve25519.Field51",
"short_module": "BN"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Lemmas",
"short_module": "SL51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Ed25519.Field51",
"short_module": "F51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
b: Lib.Buffer.lbuffer Lib.IntTypes.uint64 10ul ->
s0: Lib.IntTypes.uint64 ->
s1: Lib.IntTypes.uint64 ->
s2: Lib.IntTypes.uint64 ->
s3: Lib.IntTypes.uint64 ->
s4: Lib.IntTypes.uint64 ->
s5: Lib.IntTypes.uint64 ->
s6: Lib.IntTypes.uint64 ->
s7: Lib.IntTypes.uint64 ->
s8: Lib.IntTypes.uint64 ->
s9: Lib.IntTypes.uint64
-> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Lib.Buffer.lbuffer",
"Lib.IntTypes.uint64",
"FStar.UInt32.__uint_to_t",
"Lib.Buffer.op_Array_Assignment",
"Prims.unit"
] | [] | false | true | false | false | false | let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
| b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9 | false |
Hacl.Bignum25519.fst | Hacl.Bignum25519.reduce | val reduce:
out:felem ->
Stack unit
(requires fun h -> live h out /\ F51.mul_inv_t h out)
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.felem_fits h1 out (1, 1, 1, 1, 1) /\
F51.fevalh h0 out == F51.fevalh h1 out /\
F51.fevalh h1 out == F51.as_nat h1 out
) | val reduce:
out:felem ->
Stack unit
(requires fun h -> live h out /\ F51.mul_inv_t h out)
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.felem_fits h1 out (1, 1, 1, 1, 1) /\
F51.fevalh h0 out == F51.fevalh h1 out /\
F51.fevalh h1 out == F51.as_nat h1 out
) | let reduce out =
let (o0, o1, o2, o3, o4) = (out.(0ul), out.(1ul), out.(2ul), out.(3ul), out.(4ul)) in
let (f0, f1, f2, f3, f4) = Hacl.Spec.Curve25519.Field51.carry_felem5_full (o0, o1, o2, o3, o4) in
let (f0, f1, f2, f3, f4) = Hacl.Spec.Curve25519.Field51.subtract_p5 (f0, f1, f2, f3, f4) in
Math.Lemmas.small_mod (S51.as_nat5 (f0, f1, f2, f3, f4)) Spec.Curve25519.prime;
make_u64_5 out f0 f1 f2 f3 f4 | {
"file_name": "code/ed25519/Hacl.Bignum25519.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 31,
"end_line": 248,
"start_col": 0,
"start_line": 243
} | module Hacl.Bignum25519
module ST = FStar.HyperStack.ST
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.ByteBuffer
module LSeq = Lib.Sequence
module BSeq = Lib.ByteSequence
module S51 = Hacl.Spec.Curve25519.Field51.Definition
module SL51 = Hacl.Spec.Curve25519.Field51.Lemmas
module BN = Hacl.Impl.Curve25519.Field51
module SC = Spec.Curve25519
friend Hacl.Curve25519_51
#reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0"
inline_for_extraction noextract
let mask_51 = u64 0x7ffffffffffff
let make_u64_5 b s0 s1 s2 s3 s4 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4
let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9
let make_zero b =
b.(0ul) <- u64 0;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 0, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 0)
let make_one b =
b.(0ul) <- u64 1;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 1, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 1)
[@CInline]
let fsum out a b =
BN.fadd out a b
[@CInline]
let fdifference out a b =
BN.fsub out a b
inline_for_extraction noextract
val carry51:
#m:S51.scale64{m < 8192}
-> l:uint64
-> cin:uint64 ->
Pure (uint64 & uint64)
(requires
S51.felem_fits1 l m /\
S51.felem_fits1 cin 1)
(ensures fun (l0, l1) ->
v l + v cin == v l1 * pow2 51 + v l0 /\
S51.felem_fits1 l0 1 /\ uint_v l1 < m + 1)
let carry51 l cin =
let l' = l +! cin in
mod_mask_lemma l' 51ul;
assert (v (mod_mask #U64 #SEC 51ul) == v mask_51);
FStar.Math.Lemmas.pow2_modulo_modulo_lemma_1 (v l') 51 64;
FStar.Math.Lemmas.euclidean_division_definition (v l') (pow2 51);
FStar.Math.Lemmas.pow2_minus 64 51;
(l' &. mask_51, l' >>. 51ul)
let reduce_513 a =
let (f0, f1, f2, f3, f4) = (a.(0ul), a.(1ul), a.(2ul), a.(3ul), a.(4ul)) in
let tmp0, c0 = carry51 #9 f0 (u64 0) in
let tmp1, c1 = carry51 #10 f1 c0 in
let tmp2, c2 = carry51 #9 f2 c1 in
let tmp3, c3 = carry51 #9 f3 c2 in
let tmp4, c4 = carry51 #9 f4 c3 in
assert (S51.felem_fits5 (tmp0, tmp1, tmp2, tmp3, tmp4) (1, 1, 1, 1, 1));
SL51.lemma_carry5_simplify c0 c1 c2 c3 c4 tmp0 tmp1 tmp2 tmp3 tmp4;
assert (
S51.as_nat5 (f0, f1, f2, f3, f4) % SC.prime ==
(S51.as_nat5 (tmp0, tmp1, tmp2, tmp3, tmp4) + v c4 * 19) % SC.prime);
[@inline_let]
let tmp0', c5 = carry51 #1 tmp0 (c4 *! u64 19) in
[@inline_let]
let tmp1' = tmp1 +! c5 in
Hacl.Spec.Curve25519.Field51.lemma_mul_inv (tmp0', tmp1, tmp2, tmp3, tmp4) c5;
make_u64_5 a tmp0' tmp1' tmp2 tmp3 tmp4
[@CInline]
let fmul output input input2 =
push_frame();
let tmp = create 10ul (u128 0) in
BN.fmul output input input2 tmp;
pop_frame()
[@CInline]
let times_2 out a =
(**) let h0 = ST.get() in
let a0 = a.(0ul) in
let a1 = a.(1ul) in
let a2 = a.(2ul) in
let a3 = a.(3ul) in
let a4 = a.(4ul) in
let o0 = u64 2 *. a0 in
let o1 = u64 2 *. a1 in
let o2 = u64 2 *. a2 in
let o3 = u64 2 *. a3 in
let o4 = u64 2 *. a4 in
make_u64_5 out o0 o1 o2 o3 o4;
(**) let h1 = ST.get() in
(**) assert (S51.felem_fits1 a0 1);
(**) assert (F51.felem_fits h1 out (2, 4, 2, 2, 2));
calc (==) {
(2 * (F51.fevalh h0 a)) % SC.prime;
(==) { calc (==) {
F51.fevalh h0 a;
(==) { }
S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime;
}
}
(2 * (S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime)) % SC.prime;
(==) { FStar.Math.Lemmas.lemma_mod_mul_distr_r 2 (S51.as_nat5 (a0, a1, a2, a3, a4)) SC.prime }
(2 * S51.as_nat5 (a0, a1, a2, a3, a4)) % SC.prime;
(==) { calc (==) {
2 * S51.as_nat5 (a0, a1, a2, a3, a4);
(==) { SL51.lemma_smul_felem5 (u64 2) (a0, a1, a2, a3, a4) }
2 * v a0 + 2 * v a1 * S51.pow51 + 2 * v a2 * S51.pow51 * S51.pow51 +
2 * v a3 * S51.pow51 * S51.pow51 * S51.pow51 +
2 * v a4 * S51.pow51 * S51.pow51 * S51.pow51 * S51.pow51;
(==) {
assert_norm (2 * S51.pow51 < pow2 64);
assert_norm (4 * S51.pow51 < pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a0) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a1) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a2) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a3) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a4) (pow2 64)
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4);
}
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4) % SC.prime;
(==) { }
F51.fevalh h1 out;
}
[@CInline]
let times_d out a =
push_frame();
let d = create 5ul (u64 0) in
d.(0ul) <- u64 0x00034dca135978a3;
d.(1ul) <- u64 0x0001a8283b156ebd;
d.(2ul) <- u64 0x0005e7a26001c029;
d.(3ul) <- u64 0x000739c663a03cbb;
d.(4ul) <- u64 0x00052036cee2b6ff;
assert_norm (S51.as_nat5 (u64 0x00034dca135978a3, u64 0x0001a8283b156ebd,
u64 0x0005e7a26001c029, u64 0x000739c663a03cbb, u64 0x00052036cee2b6ff) %
Spec.Curve25519.prime == Spec.Ed25519.d);
fmul out d a;
pop_frame()
[@CInline]
let times_2d out a =
push_frame();
let d2 = create 5ul (u64 0) in
d2.(0ul) <- u64 0x00069b9426b2f159;
d2.(1ul) <- u64 0x00035050762add7a;
d2.(2ul) <- u64 0x0003cf44c0038052;
d2.(3ul) <- u64 0x0006738cc7407977;
d2.(4ul) <- u64 0x0002406d9dc56dff;
fmul out d2 a;
assert_norm (S51.as_nat5 (u64 0x00069b9426b2f159, u64 0x00035050762add7a,
u64 0x0003cf44c0038052, u64 0x0006738cc7407977, u64 0x0002406d9dc56dff) %
Spec.Curve25519.prime == 2 `SC.fmul` Spec.Ed25519.d);
pop_frame()
[@CInline]
let fsquare out a =
push_frame();
let tmp = create 5ul (u128 0) in
BN.fsqr out a tmp;
pop_frame()
[@CInline]
let fsquare_times output input count =
push_frame();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output input tmp count;
pop_frame()
[@CInline]
let fsquare_times_inplace output count =
push_frame();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output output tmp count;
pop_frame()
let inverse out a =
push_frame();
let tmp = create 10ul (u128 0) in
Hacl.Curve25519_51.finv out a tmp;
pop_frame() | {
"checked_file": "/",
"dependencies": [
"Spec.Ed25519.fst.checked",
"Spec.Curve25519.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"Lib.ByteBuffer.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Definition.fst.checked",
"Hacl.Spec.Curve25519.Field51.fst.checked",
"Hacl.Impl.Curve25519.Field51.fst.checked",
"Hacl.Curve25519_51.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Hacl.Bignum25519.fst"
} | [
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Curve25519.Field51",
"short_module": "BN"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Lemmas",
"short_module": "SL51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Ed25519.Field51",
"short_module": "F51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | out: Hacl.Bignum25519.felem -> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Hacl.Bignum25519.felem",
"Lib.IntTypes.uint64",
"Hacl.Bignum25519.make_u64_5",
"Prims.unit",
"FStar.Math.Lemmas.small_mod",
"Hacl.Spec.Curve25519.Field51.Definition.as_nat5",
"FStar.Pervasives.Native.Mktuple5",
"Spec.Curve25519.prime",
"Hacl.Spec.Curve25519.Field51.Definition.felem5",
"Hacl.Spec.Curve25519.Field51.subtract_p5",
"Prims.l_and",
"Prims.eq2",
"Spec.Curve25519.elem",
"Hacl.Spec.Curve25519.Field51.Definition.feval",
"Lib.IntTypes.int_t",
"Lib.IntTypes.U64",
"Lib.IntTypes.SEC",
"Hacl.Spec.Curve25519.Field51.Definition.felem_fits5",
"Prims.nat",
"Hacl.Spec.Curve25519.Field51.carry_felem5_full",
"FStar.Pervasives.Native.tuple5",
"Lib.Buffer.op_Array_Access",
"Lib.Buffer.MUT",
"FStar.UInt32.__uint_to_t"
] | [] | false | true | false | false | false | let reduce out =
| let o0, o1, o2, o3, o4 = (out.(0ul), out.(1ul), out.(2ul), out.(3ul), out.(4ul)) in
let f0, f1, f2, f3, f4 = Hacl.Spec.Curve25519.Field51.carry_felem5_full (o0, o1, o2, o3, o4) in
let f0, f1, f2, f3, f4 = Hacl.Spec.Curve25519.Field51.subtract_p5 (f0, f1, f2, f3, f4) in
Math.Lemmas.small_mod (S51.as_nat5 (f0, f1, f2, f3, f4)) Spec.Curve25519.prime;
make_u64_5 out f0 f1 f2 f3 f4 | false |
Hacl.Bignum25519.fst | Hacl.Bignum25519.times_d | val times_d:
out:felem
-> a:felem ->
Stack unit
(requires fun h -> live h out /\ live h a /\
F51.mul_inv_t h a
)
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.mul_inv_t h1 out /\
F51.fevalh h1 out == Spec.Ed25519.d `SC.fmul` F51.fevalh h0 a
) | val times_d:
out:felem
-> a:felem ->
Stack unit
(requires fun h -> live h out /\ live h a /\
F51.mul_inv_t h a
)
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.mul_inv_t h1 out /\
F51.fevalh h1 out == Spec.Ed25519.d `SC.fmul` F51.fevalh h0 a
) | let times_d out a =
push_frame();
let d = create 5ul (u64 0) in
d.(0ul) <- u64 0x00034dca135978a3;
d.(1ul) <- u64 0x0001a8283b156ebd;
d.(2ul) <- u64 0x0005e7a26001c029;
d.(3ul) <- u64 0x000739c663a03cbb;
d.(4ul) <- u64 0x00052036cee2b6ff;
assert_norm (S51.as_nat5 (u64 0x00034dca135978a3, u64 0x0001a8283b156ebd,
u64 0x0005e7a26001c029, u64 0x000739c663a03cbb, u64 0x00052036cee2b6ff) %
Spec.Curve25519.prime == Spec.Ed25519.d);
fmul out d a;
pop_frame() | {
"file_name": "code/ed25519/Hacl.Bignum25519.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 13,
"end_line": 192,
"start_col": 0,
"start_line": 180
} | module Hacl.Bignum25519
module ST = FStar.HyperStack.ST
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.ByteBuffer
module LSeq = Lib.Sequence
module BSeq = Lib.ByteSequence
module S51 = Hacl.Spec.Curve25519.Field51.Definition
module SL51 = Hacl.Spec.Curve25519.Field51.Lemmas
module BN = Hacl.Impl.Curve25519.Field51
module SC = Spec.Curve25519
friend Hacl.Curve25519_51
#reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0"
inline_for_extraction noextract
let mask_51 = u64 0x7ffffffffffff
let make_u64_5 b s0 s1 s2 s3 s4 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4
let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9
let make_zero b =
b.(0ul) <- u64 0;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 0, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 0)
let make_one b =
b.(0ul) <- u64 1;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 1, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 1)
[@CInline]
let fsum out a b =
BN.fadd out a b
[@CInline]
let fdifference out a b =
BN.fsub out a b
inline_for_extraction noextract
val carry51:
#m:S51.scale64{m < 8192}
-> l:uint64
-> cin:uint64 ->
Pure (uint64 & uint64)
(requires
S51.felem_fits1 l m /\
S51.felem_fits1 cin 1)
(ensures fun (l0, l1) ->
v l + v cin == v l1 * pow2 51 + v l0 /\
S51.felem_fits1 l0 1 /\ uint_v l1 < m + 1)
let carry51 l cin =
let l' = l +! cin in
mod_mask_lemma l' 51ul;
assert (v (mod_mask #U64 #SEC 51ul) == v mask_51);
FStar.Math.Lemmas.pow2_modulo_modulo_lemma_1 (v l') 51 64;
FStar.Math.Lemmas.euclidean_division_definition (v l') (pow2 51);
FStar.Math.Lemmas.pow2_minus 64 51;
(l' &. mask_51, l' >>. 51ul)
let reduce_513 a =
let (f0, f1, f2, f3, f4) = (a.(0ul), a.(1ul), a.(2ul), a.(3ul), a.(4ul)) in
let tmp0, c0 = carry51 #9 f0 (u64 0) in
let tmp1, c1 = carry51 #10 f1 c0 in
let tmp2, c2 = carry51 #9 f2 c1 in
let tmp3, c3 = carry51 #9 f3 c2 in
let tmp4, c4 = carry51 #9 f4 c3 in
assert (S51.felem_fits5 (tmp0, tmp1, tmp2, tmp3, tmp4) (1, 1, 1, 1, 1));
SL51.lemma_carry5_simplify c0 c1 c2 c3 c4 tmp0 tmp1 tmp2 tmp3 tmp4;
assert (
S51.as_nat5 (f0, f1, f2, f3, f4) % SC.prime ==
(S51.as_nat5 (tmp0, tmp1, tmp2, tmp3, tmp4) + v c4 * 19) % SC.prime);
[@inline_let]
let tmp0', c5 = carry51 #1 tmp0 (c4 *! u64 19) in
[@inline_let]
let tmp1' = tmp1 +! c5 in
Hacl.Spec.Curve25519.Field51.lemma_mul_inv (tmp0', tmp1, tmp2, tmp3, tmp4) c5;
make_u64_5 a tmp0' tmp1' tmp2 tmp3 tmp4
[@CInline]
let fmul output input input2 =
push_frame();
let tmp = create 10ul (u128 0) in
BN.fmul output input input2 tmp;
pop_frame()
[@CInline]
let times_2 out a =
(**) let h0 = ST.get() in
let a0 = a.(0ul) in
let a1 = a.(1ul) in
let a2 = a.(2ul) in
let a3 = a.(3ul) in
let a4 = a.(4ul) in
let o0 = u64 2 *. a0 in
let o1 = u64 2 *. a1 in
let o2 = u64 2 *. a2 in
let o3 = u64 2 *. a3 in
let o4 = u64 2 *. a4 in
make_u64_5 out o0 o1 o2 o3 o4;
(**) let h1 = ST.get() in
(**) assert (S51.felem_fits1 a0 1);
(**) assert (F51.felem_fits h1 out (2, 4, 2, 2, 2));
calc (==) {
(2 * (F51.fevalh h0 a)) % SC.prime;
(==) { calc (==) {
F51.fevalh h0 a;
(==) { }
S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime;
}
}
(2 * (S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime)) % SC.prime;
(==) { FStar.Math.Lemmas.lemma_mod_mul_distr_r 2 (S51.as_nat5 (a0, a1, a2, a3, a4)) SC.prime }
(2 * S51.as_nat5 (a0, a1, a2, a3, a4)) % SC.prime;
(==) { calc (==) {
2 * S51.as_nat5 (a0, a1, a2, a3, a4);
(==) { SL51.lemma_smul_felem5 (u64 2) (a0, a1, a2, a3, a4) }
2 * v a0 + 2 * v a1 * S51.pow51 + 2 * v a2 * S51.pow51 * S51.pow51 +
2 * v a3 * S51.pow51 * S51.pow51 * S51.pow51 +
2 * v a4 * S51.pow51 * S51.pow51 * S51.pow51 * S51.pow51;
(==) {
assert_norm (2 * S51.pow51 < pow2 64);
assert_norm (4 * S51.pow51 < pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a0) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a1) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a2) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a3) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a4) (pow2 64)
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4);
}
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4) % SC.prime;
(==) { }
F51.fevalh h1 out;
} | {
"checked_file": "/",
"dependencies": [
"Spec.Ed25519.fst.checked",
"Spec.Curve25519.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"Lib.ByteBuffer.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Definition.fst.checked",
"Hacl.Spec.Curve25519.Field51.fst.checked",
"Hacl.Impl.Curve25519.Field51.fst.checked",
"Hacl.Curve25519_51.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Hacl.Bignum25519.fst"
} | [
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Curve25519.Field51",
"short_module": "BN"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Lemmas",
"short_module": "SL51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Ed25519.Field51",
"short_module": "F51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | out: Hacl.Bignum25519.felem -> a: Hacl.Bignum25519.felem -> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Hacl.Bignum25519.felem",
"FStar.HyperStack.ST.pop_frame",
"Prims.unit",
"Hacl.Bignum25519.fmul",
"FStar.Pervasives.assert_norm",
"Prims.eq2",
"Prims.int",
"Prims.op_Modulus",
"Hacl.Spec.Curve25519.Field51.Definition.as_nat5",
"FStar.Pervasives.Native.Mktuple5",
"Lib.IntTypes.uint64",
"Lib.IntTypes.u64",
"Spec.Curve25519.prime",
"Spec.Ed25519.PointOps.d",
"Lib.Buffer.op_Array_Assignment",
"FStar.UInt32.__uint_to_t",
"Lib.Buffer.lbuffer_t",
"Lib.Buffer.MUT",
"Lib.IntTypes.int_t",
"Lib.IntTypes.U64",
"Lib.IntTypes.SEC",
"FStar.UInt32.uint_to_t",
"FStar.UInt32.t",
"Lib.Buffer.create",
"Lib.Buffer.lbuffer",
"FStar.HyperStack.ST.push_frame"
] | [] | false | true | false | false | false | let times_d out a =
| push_frame ();
let d = create 5ul (u64 0) in
d.(0ul) <- u64 0x00034dca135978a3;
d.(1ul) <- u64 0x0001a8283b156ebd;
d.(2ul) <- u64 0x0005e7a26001c029;
d.(3ul) <- u64 0x000739c663a03cbb;
d.(4ul) <- u64 0x00052036cee2b6ff;
assert_norm (S51.as_nat5 (u64 0x00034dca135978a3,
u64 0x0001a8283b156ebd,
u64 0x0005e7a26001c029,
u64 0x000739c663a03cbb,
u64 0x00052036cee2b6ff) %
Spec.Curve25519.prime ==
Spec.Ed25519.d);
fmul out d a;
pop_frame () | false |
Binding.fst | Binding.typedef_names | val typedef_names (d: decl) : option typedef_names | val typedef_names (d: decl) : option typedef_names | let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 13,
"end_line": 96,
"start_col": 0,
"start_line": 92
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> () | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | d: Ast.decl -> FStar.Pervasives.Native.option Ast.typedef_names | Prims.Tot | [
"total"
] | [] | [
"Ast.decl",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Ast.typedef_names",
"Prims.list",
"Ast.param",
"FStar.Pervasives.Native.option",
"Ast.expr",
"Ast.record",
"FStar.Pervasives.Native.Some",
"Ast.switch_case",
"FStar.Pervasives.Native.None"
] | [] | false | false | false | true | false | let typedef_names (d: decl) : option typedef_names =
| match d.d_decl.v with
| Record td _ _ _ | CaseType td _ _ -> Some td
| _ -> None | false |
Binding.fst | Binding.global_env_of_env | val global_env_of_env (e:env) : ML global_env | val global_env_of_env (e:env) : ML global_env | let global_env_of_env e = e.globals | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 35,
"end_line": 70,
"start_col": 0,
"start_line": 70
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> FStar.All.ML GlobalEnv.global_env | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Binding.__proj__Mkenv__item__globals",
"GlobalEnv.global_env"
] | [] | false | true | false | false | false | let global_env_of_env e =
| e.globals | false |
Binding.fst | Binding.try_lookup_enum_cases | val try_lookup_enum_cases (e: env) (i: ident) : ML (option (list ident & typ)) | val try_lookup_enum_cases (e: env) (i: ident) : ML (option (list ident & typ)) | let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 15,
"end_line": 206,
"start_col": 0,
"start_line": 201
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident
-> FStar.All.ML (FStar.Pervasives.Native.option (Prims.list Ast.ident * Ast.typ)) | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Ast.typ",
"Prims.list",
"Ast.enum_case",
"Ast.range",
"Ast.comments",
"Prims.bool",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"FStar.Pervasives.Native.Some",
"FStar.Pervasives.Native.tuple2",
"FStar.Pervasives.Native.option",
"FStar.Pervasives.Native.Mktuple2",
"Desugar.check_desugared_enum_cases",
"Ast.decl",
"FStar.Pervasives.Native.None",
"Binding.lookup"
] | [] | false | true | false | false | false | let try_lookup_enum_cases (e: env) (i: ident) : ML (option (list ident & typ)) =
| match lookup e i with
| Inr ({ d_decl = { v = Enum t _ tags } }, _) -> Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None | false |
Binding.fst | Binding.lookup_macro_name | val lookup_macro_name (e: env) (i: ident) : ML macro_signature | val lookup_macro_name (e: env) (i: ident) : ML macro_signature | let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 87,
"end_line": 192,
"start_col": 0,
"start_line": 189
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident -> FStar.All.ML GlobalEnv.macro_signature | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Ast.decl",
"GlobalEnv.macro_signature",
"Ast.either",
"Ast.typ",
"FStar.Pervasives.Native.tuple2",
"GlobalEnv.decl_attributes",
"Ast.error",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.ident'",
"Binding.lookup"
] | [] | false | true | false | false | false | let lookup_macro_name (e: env) (i: ident) : ML macro_signature =
| match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range | false |
Binding.fst | Binding.is_enum | val is_enum : e: Binding.env -> t: Ast.typ -> FStar.All.ALL Prims.bool | let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 218,
"start_col": 0,
"start_line": 214
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> t: Ast.typ -> FStar.All.ALL Prims.bool | FStar.All.ALL | [] | [] | [
"Binding.env",
"Ast.typ",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.typ'",
"Ast.ident",
"FStar.Pervasives.Native.uu___is_Some",
"FStar.Pervasives.Native.tuple2",
"Prims.list",
"Prims.bool",
"FStar.Pervasives.Native.option",
"Binding.try_lookup_enum_cases"
] | [] | false | true | false | false | false | let is_enum (e: env) (t: typ) =
| match t.v with
| Type_app i KindSpec [] -> Some? (try_lookup_enum_cases e i)
| _ -> false | false |
|
Binding.fst | Binding.lookup_macro_definition | val lookup_macro_definition (_:env) (_:ident) : ML (option expr) | val lookup_macro_definition (_:env) (_:ident) : ML (option expr) | let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 13,
"end_line": 199,
"start_col": 0,
"start_line": 194
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident -> FStar.All.ML (FStar.Pervasives.Native.option Ast.expr) | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"FStar.All.try_with",
"FStar.Pervasives.Native.option",
"Ast.expr",
"Prims.unit",
"GlobalEnv.__proj__Mkmacro_signature__item__macro_defn_t",
"GlobalEnv.macro_signature",
"Binding.lookup_macro_name",
"Prims.exn",
"FStar.Pervasives.Native.None"
] | [] | false | true | false | false | false | let lookup_macro_definition (e: env) (i: ident) =
| try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None | false |
Binding.fst | Binding.lookup_enum_cases | val lookup_enum_cases (e: env) (i: ident) : ML (list ident & typ) | val lookup_enum_cases (e: env) (i: ident) : ML (list ident & typ) | let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 93,
"end_line": 212,
"start_col": 0,
"start_line": 208
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident -> FStar.All.ML (Prims.list Ast.ident * Ast.typ) | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Prims.list",
"Ast.typ",
"FStar.Pervasives.Native.Mktuple2",
"FStar.Pervasives.Native.tuple2",
"FStar.Pervasives.Native.option",
"Ast.error",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.ident'",
"Binding.try_lookup_enum_cases"
] | [] | false | true | false | false | false | let lookup_enum_cases (e: env) (i: ident) : ML (list ident & typ) =
| match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range | false |
Binding.fst | Binding.mk_env | val mk_env (g:global_env) : ML env | val mk_env (g:global_env) : ML env | let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g } | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 17,
"end_line": 52,
"start_col": 0,
"start_line": 49
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
} | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | g: GlobalEnv.global_env -> FStar.All.ML Binding.env | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Binding.Mkenv",
"FStar.Pervasives.Native.None",
"Ast.ident",
"Binding.env",
"Binding.local_env",
"Hashtable.create",
"Ast.ident'",
"FStar.Pervasives.Native.tuple3",
"Ast.typ",
"Prims.bool",
"Hashtable.t"
] | [] | false | true | false | false | false | let mk_env (g: global_env) =
| { this = None; locals = H.create 10; globals = g } | false |
Hacl.Bignum25519.fst | Hacl.Bignum25519.times_2d | val times_2d:
out:felem
-> a:felem ->
Stack unit
(requires fun h -> live h out /\ live h a /\
F51.mul_inv_t h a
)
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.mul_inv_t h1 out /\
F51.fevalh h1 out == 2 `SC.fmul` Spec.Ed25519.d `SC.fmul` F51.fevalh h0 a
) | val times_2d:
out:felem
-> a:felem ->
Stack unit
(requires fun h -> live h out /\ live h a /\
F51.mul_inv_t h a
)
(ensures fun h0 _ h1 -> modifies (loc out) h0 h1 /\
F51.mul_inv_t h1 out /\
F51.fevalh h1 out == 2 `SC.fmul` Spec.Ed25519.d `SC.fmul` F51.fevalh h0 a
) | let times_2d out a =
push_frame();
let d2 = create 5ul (u64 0) in
d2.(0ul) <- u64 0x00069b9426b2f159;
d2.(1ul) <- u64 0x00035050762add7a;
d2.(2ul) <- u64 0x0003cf44c0038052;
d2.(3ul) <- u64 0x0006738cc7407977;
d2.(4ul) <- u64 0x0002406d9dc56dff;
fmul out d2 a;
assert_norm (S51.as_nat5 (u64 0x00069b9426b2f159, u64 0x00035050762add7a,
u64 0x0003cf44c0038052, u64 0x0006738cc7407977, u64 0x0002406d9dc56dff) %
Spec.Curve25519.prime == 2 `SC.fmul` Spec.Ed25519.d);
pop_frame() | {
"file_name": "code/ed25519/Hacl.Bignum25519.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 13,
"end_line": 208,
"start_col": 0,
"start_line": 196
} | module Hacl.Bignum25519
module ST = FStar.HyperStack.ST
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.ByteBuffer
module LSeq = Lib.Sequence
module BSeq = Lib.ByteSequence
module S51 = Hacl.Spec.Curve25519.Field51.Definition
module SL51 = Hacl.Spec.Curve25519.Field51.Lemmas
module BN = Hacl.Impl.Curve25519.Field51
module SC = Spec.Curve25519
friend Hacl.Curve25519_51
#reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0"
inline_for_extraction noextract
let mask_51 = u64 0x7ffffffffffff
let make_u64_5 b s0 s1 s2 s3 s4 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4
let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9
let make_zero b =
b.(0ul) <- u64 0;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 0, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 0)
let make_one b =
b.(0ul) <- u64 1;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 1, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 1)
[@CInline]
let fsum out a b =
BN.fadd out a b
[@CInline]
let fdifference out a b =
BN.fsub out a b
inline_for_extraction noextract
val carry51:
#m:S51.scale64{m < 8192}
-> l:uint64
-> cin:uint64 ->
Pure (uint64 & uint64)
(requires
S51.felem_fits1 l m /\
S51.felem_fits1 cin 1)
(ensures fun (l0, l1) ->
v l + v cin == v l1 * pow2 51 + v l0 /\
S51.felem_fits1 l0 1 /\ uint_v l1 < m + 1)
let carry51 l cin =
let l' = l +! cin in
mod_mask_lemma l' 51ul;
assert (v (mod_mask #U64 #SEC 51ul) == v mask_51);
FStar.Math.Lemmas.pow2_modulo_modulo_lemma_1 (v l') 51 64;
FStar.Math.Lemmas.euclidean_division_definition (v l') (pow2 51);
FStar.Math.Lemmas.pow2_minus 64 51;
(l' &. mask_51, l' >>. 51ul)
let reduce_513 a =
let (f0, f1, f2, f3, f4) = (a.(0ul), a.(1ul), a.(2ul), a.(3ul), a.(4ul)) in
let tmp0, c0 = carry51 #9 f0 (u64 0) in
let tmp1, c1 = carry51 #10 f1 c0 in
let tmp2, c2 = carry51 #9 f2 c1 in
let tmp3, c3 = carry51 #9 f3 c2 in
let tmp4, c4 = carry51 #9 f4 c3 in
assert (S51.felem_fits5 (tmp0, tmp1, tmp2, tmp3, tmp4) (1, 1, 1, 1, 1));
SL51.lemma_carry5_simplify c0 c1 c2 c3 c4 tmp0 tmp1 tmp2 tmp3 tmp4;
assert (
S51.as_nat5 (f0, f1, f2, f3, f4) % SC.prime ==
(S51.as_nat5 (tmp0, tmp1, tmp2, tmp3, tmp4) + v c4 * 19) % SC.prime);
[@inline_let]
let tmp0', c5 = carry51 #1 tmp0 (c4 *! u64 19) in
[@inline_let]
let tmp1' = tmp1 +! c5 in
Hacl.Spec.Curve25519.Field51.lemma_mul_inv (tmp0', tmp1, tmp2, tmp3, tmp4) c5;
make_u64_5 a tmp0' tmp1' tmp2 tmp3 tmp4
[@CInline]
let fmul output input input2 =
push_frame();
let tmp = create 10ul (u128 0) in
BN.fmul output input input2 tmp;
pop_frame()
[@CInline]
let times_2 out a =
(**) let h0 = ST.get() in
let a0 = a.(0ul) in
let a1 = a.(1ul) in
let a2 = a.(2ul) in
let a3 = a.(3ul) in
let a4 = a.(4ul) in
let o0 = u64 2 *. a0 in
let o1 = u64 2 *. a1 in
let o2 = u64 2 *. a2 in
let o3 = u64 2 *. a3 in
let o4 = u64 2 *. a4 in
make_u64_5 out o0 o1 o2 o3 o4;
(**) let h1 = ST.get() in
(**) assert (S51.felem_fits1 a0 1);
(**) assert (F51.felem_fits h1 out (2, 4, 2, 2, 2));
calc (==) {
(2 * (F51.fevalh h0 a)) % SC.prime;
(==) { calc (==) {
F51.fevalh h0 a;
(==) { }
S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime;
}
}
(2 * (S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime)) % SC.prime;
(==) { FStar.Math.Lemmas.lemma_mod_mul_distr_r 2 (S51.as_nat5 (a0, a1, a2, a3, a4)) SC.prime }
(2 * S51.as_nat5 (a0, a1, a2, a3, a4)) % SC.prime;
(==) { calc (==) {
2 * S51.as_nat5 (a0, a1, a2, a3, a4);
(==) { SL51.lemma_smul_felem5 (u64 2) (a0, a1, a2, a3, a4) }
2 * v a0 + 2 * v a1 * S51.pow51 + 2 * v a2 * S51.pow51 * S51.pow51 +
2 * v a3 * S51.pow51 * S51.pow51 * S51.pow51 +
2 * v a4 * S51.pow51 * S51.pow51 * S51.pow51 * S51.pow51;
(==) {
assert_norm (2 * S51.pow51 < pow2 64);
assert_norm (4 * S51.pow51 < pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a0) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a1) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a2) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a3) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a4) (pow2 64)
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4);
}
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4) % SC.prime;
(==) { }
F51.fevalh h1 out;
}
[@CInline]
let times_d out a =
push_frame();
let d = create 5ul (u64 0) in
d.(0ul) <- u64 0x00034dca135978a3;
d.(1ul) <- u64 0x0001a8283b156ebd;
d.(2ul) <- u64 0x0005e7a26001c029;
d.(3ul) <- u64 0x000739c663a03cbb;
d.(4ul) <- u64 0x00052036cee2b6ff;
assert_norm (S51.as_nat5 (u64 0x00034dca135978a3, u64 0x0001a8283b156ebd,
u64 0x0005e7a26001c029, u64 0x000739c663a03cbb, u64 0x00052036cee2b6ff) %
Spec.Curve25519.prime == Spec.Ed25519.d);
fmul out d a;
pop_frame() | {
"checked_file": "/",
"dependencies": [
"Spec.Ed25519.fst.checked",
"Spec.Curve25519.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"Lib.ByteBuffer.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Definition.fst.checked",
"Hacl.Spec.Curve25519.Field51.fst.checked",
"Hacl.Impl.Curve25519.Field51.fst.checked",
"Hacl.Curve25519_51.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Hacl.Bignum25519.fst"
} | [
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Curve25519.Field51",
"short_module": "BN"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Lemmas",
"short_module": "SL51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Ed25519.Field51",
"short_module": "F51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | out: Hacl.Bignum25519.felem -> a: Hacl.Bignum25519.felem -> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Hacl.Bignum25519.felem",
"FStar.HyperStack.ST.pop_frame",
"Prims.unit",
"FStar.Pervasives.assert_norm",
"Prims.eq2",
"Prims.int",
"Prims.op_Modulus",
"Hacl.Spec.Curve25519.Field51.Definition.as_nat5",
"FStar.Pervasives.Native.Mktuple5",
"Lib.IntTypes.uint64",
"Lib.IntTypes.u64",
"Spec.Curve25519.prime",
"Spec.Curve25519.fmul",
"Spec.Ed25519.PointOps.d",
"Hacl.Bignum25519.fmul",
"Lib.Buffer.op_Array_Assignment",
"FStar.UInt32.__uint_to_t",
"Lib.Buffer.lbuffer_t",
"Lib.Buffer.MUT",
"Lib.IntTypes.int_t",
"Lib.IntTypes.U64",
"Lib.IntTypes.SEC",
"FStar.UInt32.uint_to_t",
"FStar.UInt32.t",
"Lib.Buffer.create",
"Lib.Buffer.lbuffer",
"FStar.HyperStack.ST.push_frame"
] | [] | false | true | false | false | false | let times_2d out a =
| push_frame ();
let d2 = create 5ul (u64 0) in
d2.(0ul) <- u64 0x00069b9426b2f159;
d2.(1ul) <- u64 0x00035050762add7a;
d2.(2ul) <- u64 0x0003cf44c0038052;
d2.(3ul) <- u64 0x0006738cc7407977;
d2.(4ul) <- u64 0x0002406d9dc56dff;
fmul out d2 a;
assert_norm (S51.as_nat5 (u64 0x00069b9426b2f159,
u64 0x00035050762add7a,
u64 0x0003cf44c0038052,
u64 0x0006738cc7407977,
u64 0x0002406d9dc56dff) %
Spec.Curve25519.prime ==
2
`SC.fmul`
Spec.Ed25519.d);
pop_frame () | false |
Binding.fst | Binding.unfold_typ_abbrev_only | val unfold_typ_abbrev_only (_:env) (t:typ) : ML typ | val unfold_typ_abbrev_only (_:env) (t:typ) : ML typ | let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 10,
"end_line": 321,
"start_col": 0,
"start_line": 308
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> t: Ast.typ -> FStar.All.ML Ast.typ | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.typ",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.typ'",
"Ast.ident",
"Ast.t_kind",
"Ast.decl",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Binding.unfold_typ_abbrev_only",
"FStar.Pervasives.Native.option",
"FStar.Pervasives.Native.tuple2",
"Binding.try_lookup"
] | [
"recursion"
] | false | true | false | false | false | let rec unfold_typ_abbrev_only (env: env) (t: typ) : ML typ =
| match t.v with
| Type_app hd _ [] ->
(match try_lookup env hd with
| Some (Inr (d, _)) ->
(match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t)
| _ -> t)
| _ -> t | false |
Binding.fst | Binding.unfold_typ_abbrev_and_enum | val unfold_typ_abbrev_and_enum (env: env) (t: typ) : ML typ | val unfold_typ_abbrev_and_enum (env: env) (t: typ) : ML typ | let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 10,
"end_line": 353,
"start_col": 0,
"start_line": 339
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found" | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> t: Ast.typ -> FStar.All.ML Ast.typ | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.typ",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.typ'",
"Ast.ident",
"Ast.t_kind",
"Ast.decl",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Binding.unfold_typ_abbrev_and_enum",
"Prims.list",
"Ast.enum_case",
"FStar.Pervasives.Native.tuple2",
"Binding.lookup"
] | [
"recursion"
] | false | true | false | false | false | let rec unfold_typ_abbrev_and_enum (env: env) (t: typ) : ML typ =
| match t.v with
| Type_app hd _ [] ->
(match lookup env hd with
| Inr (d, _) ->
(match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t)
| _ -> t)
| _ -> t | false |
Binding.fst | Binding.env_of_global_env | val env_of_global_env: global_env -> env | val env_of_global_env: global_env -> env | let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g } | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 49,
"end_line": 67,
"start_col": 0,
"start_line": 64
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
} | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | _: GlobalEnv.global_env -> Binding.env | Prims.Tot | [
"total"
] | [] | [
"GlobalEnv.global_env",
"Binding.Mkenv",
"FStar.Pervasives.Native.None",
"Ast.ident",
"Binding.env",
"Hashtable.t",
"Ast.ident'",
"FStar.Pervasives.Native.tuple3",
"Ast.typ",
"Prims.bool",
"Hashtable.create"
] | [] | false | false | false | true | false | let env_of_global_env: global_env -> env =
| let locals = H.create 1 in
fun g -> { this = None; locals = locals; globals = g } | false |
Binding.fst | Binding.copy_env | val copy_env : e: Binding.env -> FStar.All.ALL Binding.env | let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
} | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 3,
"end_line": 61,
"start_col": 0,
"start_line": 54
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g } | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> FStar.All.ALL Binding.env | FStar.All.ALL | [
"trivial_postcondition"
] | [] | [
"Binding.env",
"Binding.Mkenv",
"Binding.__proj__Mkenv__item__this",
"Binding.__proj__Mkenv__item__globals",
"Prims.unit",
"Hashtable.iter",
"Ast.ident'",
"FStar.Pervasives.Native.tuple3",
"Ast.typ",
"Prims.bool",
"Hashtable.insert",
"Binding.__proj__Mkenv__item__locals",
"Hashtable.t",
"Hashtable.create"
] | [] | false | true | false | false | false | let copy_env (e: env) =
| let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{ this = e.this; globals = e.globals; locals = locals } | false |
|
Binding.fst | Binding.local_env | val local_env : Type0 | let local_env = H.t ident' (ident' & typ & bool) | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 48,
"end_line": 37,
"start_col": 0,
"start_line": 37
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
/// | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | Type0 | Prims.Tot | [
"total"
] | [] | [
"Hashtable.t",
"Ast.ident'",
"FStar.Pervasives.Native.tuple3",
"Ast.typ",
"Prims.bool"
] | [] | false | false | false | true | true | let local_env =
| H.t ident' (ident' & typ & bool) | false |
|
Binding.fst | Binding.check_shadow | val check_shadow : e: Hashtable.t Ast.ident' 'a -> i: Ast.ident -> r: Ast.range -> FStar.All.ALL Prims.unit | let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> () | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 11,
"end_line": 90,
"start_col": 0,
"start_line": 85
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> [] | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Hashtable.t Ast.ident' 'a -> i: Ast.ident -> r: Ast.range -> FStar.All.ALL Prims.unit | FStar.All.ALL | [] | [] | [
"Hashtable.t",
"Ast.ident'",
"Ast.ident",
"Ast.range",
"Ast.error",
"Prims.unit",
"Ast.__proj__Mkwith_meta_t__item__range",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"FStar.Pervasives.Native.option",
"Hashtable.try_find",
"Ast.__proj__Mkwith_meta_t__item__v"
] | [] | false | true | false | false | false | let check_shadow (e: H.t ident' 'a) (i: ident) (r: range) =
| match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> () | false |
|
Binding.fst | Binding.resolve_record_case_output_extern_type_name | val resolve_record_case_output_extern_type_name (_:env) (_:ident): ML ident | val resolve_record_case_output_extern_type_name (_:env) (_:ident): ML ident | let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i)) | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 18,
"end_line": 180,
"start_col": 0,
"start_line": 169
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> () | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> i: Ast.ident -> FStar.All.ML Ast.ident | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Ast.typedef_names",
"Prims.list",
"Ast.out_field",
"Prims.bool",
"Ast.range",
"Ast.comments",
"Ast.__proj__Mktypedef_names__item__typedef_abbrev",
"FStar.Pervasives.Native.option",
"Ast.decl",
"Ast.param",
"Ast.expr",
"Ast.record",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"Ast.__proj__Mktypedef_names__item__typedef_name",
"Ast.switch_case",
"Ast.typ",
"FStar.Pervasives.Native.tuple2",
"Binding.lookup",
"Hashtable.try_find",
"Ast.ident'",
"Ast.__proj__Mkwith_meta_t__item__v",
"Hashtable.t",
"GlobalEnv.__proj__Mkglobal_env__item__ge_extern_t",
"GlobalEnv.global_env",
"Binding.global_env_of_env",
"GlobalEnv.__proj__Mkglobal_env__item__ge_out_t"
] | [] | false | true | false | false | false | let resolve_record_case_output_extern_type_name (env: env) (i: ident) =
| match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some { d_decl = { v = OutputType { out_typ_names = names } } } -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some { d_decl = { v = ExternType td_names } } -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({ d_decl = { v = Record names _ _ _ } }, _)
| Inr ({ d_decl = { v = CaseType names _ _ } }, _) -> names.typedef_name
| _ -> i)) | false |
Binding.fst | Binding.lookup | val lookup (e: env) (i: ident) : ML (either typ (decl & either decl_attributes macro_signature)) | val lookup (e: env) (i: ident) : ML (either typ (decl & either decl_attributes macro_signature)) | let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 15,
"end_line": 160,
"start_col": 0,
"start_line": 157
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident
-> FStar.All.ML
(Ast.either Ast.typ (Ast.decl * Ast.either GlobalEnv.decl_attributes GlobalEnv.macro_signature)) | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Ast.error",
"Ast.either",
"Ast.typ",
"FStar.Pervasives.Native.tuple2",
"Ast.decl",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.ident'",
"FStar.Pervasives.Native.option",
"Binding.try_lookup"
] | [] | false | true | false | false | false | let lookup (e: env) (i: ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
| match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v | false |
Binding.fst | Binding.eq_typ | val eq_typ : env: Binding.env -> t1: Ast.typ -> t2: Ast.typ -> FStar.All.ALL Prims.bool | let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2) | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 89,
"end_line": 382,
"start_col": 0,
"start_line": 380
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> t1: Ast.typ -> t2: Ast.typ -> FStar.All.ALL Prims.bool | FStar.All.ALL | [] | [] | [
"Binding.env",
"Ast.typ",
"Ast.eq_typ",
"Prims.bool",
"Binding.unfold_typ_abbrev_and_enum"
] | [] | false | true | false | false | false | let eq_typ env t1 t2 =
| if Ast.eq_typ t1 t2
then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2) | false |
|
Binding.fst | Binding.is_used | val is_used (e: env) (i: ident) : ML bool | val is_used (e: env) (i: ident) : ML bool | let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 84,
"end_line": 223,
"start_col": 0,
"start_line": 220
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident -> FStar.All.ML Prims.bool | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Ast.ident'",
"Ast.typ",
"Prims.bool",
"FStar.Pervasives.Native.option",
"FStar.Pervasives.Native.tuple3",
"Ast.error",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"Ast.__proj__Mkwith_meta_t__item__range",
"Hashtable.try_find",
"Binding.__proj__Mkenv__item__locals",
"Ast.__proj__Mkwith_meta_t__item__v"
] | [] | false | true | false | false | false | let is_used (e: env) (i: ident) : ML bool =
| match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range | false |
Binding.fst | Binding._and_ | val _and_ : b1: Prims.bool -> b2: Prims.bool -> Prims.bool | let _and_ b1 b2 = b1 && b2 | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 26,
"end_line": 405,
"start_col": 0,
"start_line": 405
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | b1: Prims.bool -> b2: Prims.bool -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Prims.bool",
"Prims.op_AmpAmp"
] | [] | false | false | false | true | false | let _and_ b1 b2 =
| b1 && b2 | false |
|
Binding.fst | Binding.params_of_decl | val params_of_decl (d: decl) : list param | val params_of_decl (d: decl) : list param | let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> [] | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 23,
"end_line": 83,
"start_col": 0,
"start_line": 72
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | d: Ast.decl -> Prims.list Ast.param | Prims.Tot | [
"total"
] | [] | [
"Ast.decl",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Ast.ident",
"Prims.Nil",
"Ast.param",
"FStar.Pervasives.Native.option",
"Ast.typ",
"Ast.constant",
"Prims.list",
"Ast.enum_case",
"Ast.typedef_names",
"Ast.expr",
"Ast.record",
"Ast.switch_case",
"Ast.out_typ"
] | [] | false | false | false | true | false | let params_of_decl (d: decl) : list param =
| match d.d_decl.v with
| ModuleAbbrev _ _ | Define _ _ _ | TypeAbbrev _ _ | Enum _ _ _ -> []
| Record _ params _ _ | CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> [] | false |
Binding.fst | Binding.eq_typs | val eq_typs : env: Binding.env -> ts: Prims.list (Ast.typ * Ast.typ) -> FStar.All.ML Prims.bool | let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 52,
"end_line": 385,
"start_col": 0,
"start_line": 384
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> ts: Prims.list (Ast.typ * Ast.typ) -> FStar.All.ML Prims.bool | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Prims.list",
"FStar.Pervasives.Native.tuple2",
"Ast.typ",
"FStar.List.for_all",
"Binding.eq_typ",
"Prims.bool"
] | [] | false | true | false | false | false | let eq_typs env ts =
| List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts | false |
|
Binding.fst | Binding.cast | val cast : e: Ast.with_meta_t Ast.expr' -> t: Ast.integer_type -> t': Ast.integer_type
-> Ast.with_meta_t Ast.expr' | let cast e t t' = { e with v = App (Cast (Some t) t') [e] } | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 59,
"end_line": 387,
"start_col": 0,
"start_line": 387
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Ast.with_meta_t Ast.expr' -> t: Ast.integer_type -> t': Ast.integer_type
-> Ast.with_meta_t Ast.expr' | Prims.Tot | [
"total"
] | [] | [
"Ast.with_meta_t",
"Ast.expr'",
"Ast.integer_type",
"Ast.Mkwith_meta_t",
"Ast.App",
"Ast.Cast",
"FStar.Pervasives.Native.Some",
"Prims.Cons",
"Prims.Nil",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.__proj__Mkwith_meta_t__item__comments"
] | [] | false | false | false | true | false | let cast e t t' =
| { e with v = App (Cast (Some t) t') [e] } | false |
|
Binding.fst | Binding.try_lookup | val try_lookup (e: env) (i: ident)
: ML (option (either typ (decl & either decl_attributes macro_signature))) | val try_lookup (e: env) (i: ident)
: ML (option (either typ (decl & either decl_attributes macro_signature))) | let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 18,
"end_line": 155,
"start_col": 0,
"start_line": 144
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident
-> FStar.All.ML
(FStar.Pervasives.Native.option (Ast.either Ast.typ
(Ast.decl * Ast.either GlobalEnv.decl_attributes GlobalEnv.macro_signature))) | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Ast.ident'",
"Ast.typ",
"FStar.Pervasives.Native.Some",
"Ast.either",
"FStar.Pervasives.Native.tuple2",
"Ast.decl",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"Ast.Inl",
"FStar.Pervasives.Native.option",
"Prims.unit",
"Hashtable.insert",
"FStar.Pervasives.Native.tuple3",
"Prims.bool",
"Binding.__proj__Mkenv__item__locals",
"Ast.__proj__Mkwith_meta_t__item__v",
"FStar.Pervasives.Native.Mktuple3",
"Hashtable.remove",
"Ast.Inr",
"FStar.Pervasives.Native.None",
"Hashtable.try_find",
"GlobalEnv.__proj__Mkglobal_env__item__ge_h",
"Binding.__proj__Mkenv__item__globals"
] | [] | false | true | false | false | false | let try_lookup (e: env) (i: ident)
: ML (option (either typ (decl & either decl_attributes macro_signature))) =
| match H.try_find e.locals i.v with
| Some (_, t, true) -> Some (Inl t)
| Some (j, t, false) ->
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None | false |
Binding.fst | Binding.remove_local | val remove_local (e: env) (i: ident) : ML unit | val remove_local (e: env) (i: ident) : ML unit | let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> () | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 11,
"end_line": 167,
"start_col": 0,
"start_line": 162
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Ast.ident'",
"Ast.typ",
"Prims.bool",
"Hashtable.remove",
"FStar.Pervasives.Native.tuple3",
"Binding.__proj__Mkenv__item__locals",
"Prims.unit",
"Ast.__proj__Mkwith_meta_t__item__v",
"FStar.Pervasives.Native.option",
"Hashtable.try_find"
] | [] | false | true | false | false | false | let remove_local (e: env) (i: ident) : ML unit =
| match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> () | false |
Binding.fst | Binding._or_ | val _or_ : b1: Prims.bool -> b2: Prims.bool -> Prims.bool | let _or_ b1 b2 = b1 || b2 | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 25,
"end_line": 404,
"start_col": 0,
"start_line": 404
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | b1: Prims.bool -> b2: Prims.bool -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Prims.bool",
"Prims.op_BarBar"
] | [] | false | false | false | true | false | let _or_ b1 b2 =
| b1 || b2 | false |
|
Binding.fst | Binding.type_of_integer_type | val type_of_integer_type : _: Ast.integer_type -> Ast.with_meta_t Ast.typ' | let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64 | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 21,
"end_line": 229,
"start_col": 0,
"start_line": 225
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | _: Ast.integer_type -> Ast.with_meta_t Ast.typ' | Prims.Tot | [
"total"
] | [] | [
"Ast.integer_type",
"Ast.tuint8",
"Ast.tuint16",
"Ast.tuint32",
"Ast.tuint64",
"Ast.with_meta_t",
"Ast.typ'"
] | [] | false | false | false | true | false | let type_of_integer_type =
| function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64 | false |
|
Binding.fst | Binding.format_identifier | val format_identifier (e: env) (i: ident) : ML ident | val format_identifier (e: env) (i: ident) : ML ident | let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 21,
"end_line": 116,
"start_col": 0,
"start_line": 98
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident -> FStar.All.ML Ast.ident | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"FStar.Pervasives.Native.tuple2",
"FStar.Pervasives.Native.option",
"Ast.decl",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"FStar.Pervasives.Native.tuple3",
"Ast.ident'",
"Ast.typ",
"Prims.bool",
"Ast.error",
"Ast.__proj__Mkwith_meta_t__item__range",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"FStar.Pervasives.Native.Mktuple2",
"Hashtable.try_find",
"Binding.__proj__Mkenv__item__locals",
"Ast.__proj__Mkwith_meta_t__item__v",
"GlobalEnv.__proj__Mkglobal_env__item__ge_h",
"Binding.__proj__Mkenv__item__globals",
"Ast.with_meta_t",
"FStar.String.list_of_string",
"Ast.__proj__Mkident'__item__name",
"FStar.All.failwith",
"FStar.String.char",
"Prims.list",
"Prims.op_Equality",
"FStar.Char.char",
"FStar.Char.lowercase",
"Ast.Mkwith_meta_t",
"Ast.Mkident'",
"Ast.__proj__Mkident'__item__modul_name",
"Prims.op_Hat",
"Ast.reserved_prefix",
"Ast.__proj__Mkwith_meta_t__item__comments"
] | [] | false | true | false | false | false | let format_identifier (e: env) (i: ident) : ML ident =
| let j =
match String.list_of_string i.v.name with
| [] -> failwith "Impossible: empty identifier"
| c0 :: cs ->
if FStar.Char.lowercase c0 = c0
then i
else { i with v = { i.v with name = Ast.reserved_prefix ^ i.v.name } }
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg =
Printf.sprintf "This name (%s) starts will clash with another name in scope (%s) as it is translated. Please rename it"
(ident_to_string i)
(ident_to_string j)
in
error msg i.range | false |
Binding.fst | Binding.check_integer_bounds | val check_integer_bounds : t: Ast.integer_type -> i: Prims.int -> Prims.bool | let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64 | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 36,
"end_line": 236,
"start_col": 0,
"start_line": 231
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64 | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | t: Ast.integer_type -> i: Prims.int -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Ast.integer_type",
"Prims.int",
"FStar.UInt.fits",
"Prims.bool"
] | [] | false | false | false | true | false | let check_integer_bounds t i =
| match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64 | false |
|
Binding.fst | Binding.lookup_expr_name | val lookup_expr_name (_:env) (_:ident) : ML typ | val lookup_expr_name (_:env) (_:ident) : ML typ | let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 100,
"end_line": 187,
"start_col": 0,
"start_line": 182
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i)) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident -> FStar.All.ML Ast.typ | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Ast.typ",
"Ast.decl",
"FStar.Pervasives.Native.option",
"Ast.expr",
"FStar.Pervasives.Native.tuple2",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"Ast.error",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.ident'",
"Binding.lookup"
] | [] | false | true | false | false | false | let lookup_expr_name (e: env) (i: ident) : ML typ =
| match lookup e i with
| Inl t -> t
| Inr (_, Inr { macro_arguments_t = [] ; macro_result_t = t }) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range | false |
Binding.fst | Binding.add_global | val add_global (e: global_env) (i: ident) (d: decl) (t: either decl_attributes macro_signature)
: ML unit | val add_global (e: global_env) (i: ident) (d: decl) (t: either decl_attributes macro_signature)
: ML unit | let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 7,
"end_line": 135,
"start_col": 0,
"start_line": 118
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
e: GlobalEnv.global_env ->
i: Ast.ident ->
d: Ast.decl ->
t: Ast.either GlobalEnv.decl_attributes GlobalEnv.macro_signature
-> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.decl",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"Binding.typedef_names",
"Prims.unit",
"Ast.typedef_names",
"Prims.op_disEquality",
"Ast.ident'",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.__proj__Mktypedef_names__item__typedef_abbrev",
"FStar.Pervasives.Native.Mktuple2",
"Binding.format_identifier",
"Binding.check_shadow",
"FStar.Pervasives.Native.tuple2",
"GlobalEnv.__proj__Mkglobal_env__item__ge_h",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Prims.bool",
"Binding.env",
"Binding.mk_env",
"Hashtable.insert"
] | [] | false | true | false | false | false | let add_global (e: global_env) (i: ident) (d: decl) (t: either decl_attributes macro_signature)
: ML unit =
| let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then
(check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)) | false |
Binding.fst | Binding.add_local | val add_local (e: env) (i: ident) (t: typ) : ML unit | val add_local (e: env) (i: ident) (t: typ) : ML unit | let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false) | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 41,
"end_line": 142,
"start_col": 0,
"start_line": 137
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: Binding.env -> i: Ast.ident -> t: Ast.typ -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Ast.typ",
"Hashtable.insert",
"Ast.ident'",
"FStar.Pervasives.Native.tuple3",
"Prims.bool",
"Binding.__proj__Mkenv__item__locals",
"Ast.__proj__Mkwith_meta_t__item__v",
"FStar.Pervasives.Native.Mktuple3",
"Prims.unit",
"Binding.format_identifier",
"Binding.check_shadow",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.typ'",
"FStar.Pervasives.Native.tuple2",
"Ast.decl",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"GlobalEnv.__proj__Mkglobal_env__item__ge_h",
"Binding.__proj__Mkenv__item__globals"
] | [] | false | true | false | false | false | let add_local (e: env) (i: ident) (t: typ) : ML unit =
| check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false) | false |
Binding.fst | Binding.check_output_type | val check_output_type (ge: global_env) (t: typ) : ML ident | val check_output_type (ge: global_env) (t: typ) : ML ident | let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err () | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 15,
"end_line": 525,
"start_col": 0,
"start_line": 520
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | ge: GlobalEnv.global_env -> t: Ast.typ -> FStar.All.ML Ast.ident | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.typ",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.typ'",
"Ast.ident",
"Prims.unit",
"Ast.error",
"Ast.__proj__Mkwith_meta_t__item__range",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.print_typ"
] | [] | false | true | false | false | false | let check_output_type (ge: global_env) (t: typ) : ML ident =
| let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range
in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err () | false |
Hacl.Bignum25519.fst | Hacl.Bignum25519.store_51 | val store_51:
output:lbuffer uint8 32ul
-> input:lbuffer uint64 5ul ->
Stack unit
(requires fun h -> live h input /\ live h output /\ F51.mul_inv_t h input)
(ensures fun h0 _ h1 -> modifies (loc output) h0 h1 /\
as_seq h1 output == BSeq.nat_to_bytes_le 32 (F51.fevalh h0 input)
) | val store_51:
output:lbuffer uint8 32ul
-> input:lbuffer uint64 5ul ->
Stack unit
(requires fun h -> live h input /\ live h output /\ F51.mul_inv_t h input)
(ensures fun h0 _ h1 -> modifies (loc output) h0 h1 /\
as_seq h1 output == BSeq.nat_to_bytes_le 32 (F51.fevalh h0 input)
) | let store_51 output input =
let h0 = ST.get () in
push_frame ();
let u64s = create 4ul (u64 0) in
BN.store_felem u64s input;
let h1 = ST.get () in
assert (as_seq h1 u64s == BSeq.nat_to_intseq_le 4 (F51.fevalh h0 input));
uints_to_bytes_le 4ul output u64s;
BSeq.uints_to_bytes_le_nat_lemma #U64 #SEC 4 (F51.fevalh h0 input);
pop_frame () | {
"file_name": "code/ed25519/Hacl.Bignum25519.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 14,
"end_line": 288,
"start_col": 0,
"start_line": 279
} | module Hacl.Bignum25519
module ST = FStar.HyperStack.ST
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.ByteBuffer
module LSeq = Lib.Sequence
module BSeq = Lib.ByteSequence
module S51 = Hacl.Spec.Curve25519.Field51.Definition
module SL51 = Hacl.Spec.Curve25519.Field51.Lemmas
module BN = Hacl.Impl.Curve25519.Field51
module SC = Spec.Curve25519
friend Hacl.Curve25519_51
#reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0"
inline_for_extraction noextract
let mask_51 = u64 0x7ffffffffffff
let make_u64_5 b s0 s1 s2 s3 s4 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4
let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9
let make_zero b =
b.(0ul) <- u64 0;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 0, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 0)
let make_one b =
b.(0ul) <- u64 1;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 1, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 1)
[@CInline]
let fsum out a b =
BN.fadd out a b
[@CInline]
let fdifference out a b =
BN.fsub out a b
inline_for_extraction noextract
val carry51:
#m:S51.scale64{m < 8192}
-> l:uint64
-> cin:uint64 ->
Pure (uint64 & uint64)
(requires
S51.felem_fits1 l m /\
S51.felem_fits1 cin 1)
(ensures fun (l0, l1) ->
v l + v cin == v l1 * pow2 51 + v l0 /\
S51.felem_fits1 l0 1 /\ uint_v l1 < m + 1)
let carry51 l cin =
let l' = l +! cin in
mod_mask_lemma l' 51ul;
assert (v (mod_mask #U64 #SEC 51ul) == v mask_51);
FStar.Math.Lemmas.pow2_modulo_modulo_lemma_1 (v l') 51 64;
FStar.Math.Lemmas.euclidean_division_definition (v l') (pow2 51);
FStar.Math.Lemmas.pow2_minus 64 51;
(l' &. mask_51, l' >>. 51ul)
let reduce_513 a =
let (f0, f1, f2, f3, f4) = (a.(0ul), a.(1ul), a.(2ul), a.(3ul), a.(4ul)) in
let tmp0, c0 = carry51 #9 f0 (u64 0) in
let tmp1, c1 = carry51 #10 f1 c0 in
let tmp2, c2 = carry51 #9 f2 c1 in
let tmp3, c3 = carry51 #9 f3 c2 in
let tmp4, c4 = carry51 #9 f4 c3 in
assert (S51.felem_fits5 (tmp0, tmp1, tmp2, tmp3, tmp4) (1, 1, 1, 1, 1));
SL51.lemma_carry5_simplify c0 c1 c2 c3 c4 tmp0 tmp1 tmp2 tmp3 tmp4;
assert (
S51.as_nat5 (f0, f1, f2, f3, f4) % SC.prime ==
(S51.as_nat5 (tmp0, tmp1, tmp2, tmp3, tmp4) + v c4 * 19) % SC.prime);
[@inline_let]
let tmp0', c5 = carry51 #1 tmp0 (c4 *! u64 19) in
[@inline_let]
let tmp1' = tmp1 +! c5 in
Hacl.Spec.Curve25519.Field51.lemma_mul_inv (tmp0', tmp1, tmp2, tmp3, tmp4) c5;
make_u64_5 a tmp0' tmp1' tmp2 tmp3 tmp4
[@CInline]
let fmul output input input2 =
push_frame();
let tmp = create 10ul (u128 0) in
BN.fmul output input input2 tmp;
pop_frame()
[@CInline]
let times_2 out a =
(**) let h0 = ST.get() in
let a0 = a.(0ul) in
let a1 = a.(1ul) in
let a2 = a.(2ul) in
let a3 = a.(3ul) in
let a4 = a.(4ul) in
let o0 = u64 2 *. a0 in
let o1 = u64 2 *. a1 in
let o2 = u64 2 *. a2 in
let o3 = u64 2 *. a3 in
let o4 = u64 2 *. a4 in
make_u64_5 out o0 o1 o2 o3 o4;
(**) let h1 = ST.get() in
(**) assert (S51.felem_fits1 a0 1);
(**) assert (F51.felem_fits h1 out (2, 4, 2, 2, 2));
calc (==) {
(2 * (F51.fevalh h0 a)) % SC.prime;
(==) { calc (==) {
F51.fevalh h0 a;
(==) { }
S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime;
}
}
(2 * (S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime)) % SC.prime;
(==) { FStar.Math.Lemmas.lemma_mod_mul_distr_r 2 (S51.as_nat5 (a0, a1, a2, a3, a4)) SC.prime }
(2 * S51.as_nat5 (a0, a1, a2, a3, a4)) % SC.prime;
(==) { calc (==) {
2 * S51.as_nat5 (a0, a1, a2, a3, a4);
(==) { SL51.lemma_smul_felem5 (u64 2) (a0, a1, a2, a3, a4) }
2 * v a0 + 2 * v a1 * S51.pow51 + 2 * v a2 * S51.pow51 * S51.pow51 +
2 * v a3 * S51.pow51 * S51.pow51 * S51.pow51 +
2 * v a4 * S51.pow51 * S51.pow51 * S51.pow51 * S51.pow51;
(==) {
assert_norm (2 * S51.pow51 < pow2 64);
assert_norm (4 * S51.pow51 < pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a0) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a1) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a2) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a3) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a4) (pow2 64)
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4);
}
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4) % SC.prime;
(==) { }
F51.fevalh h1 out;
}
[@CInline]
let times_d out a =
push_frame();
let d = create 5ul (u64 0) in
d.(0ul) <- u64 0x00034dca135978a3;
d.(1ul) <- u64 0x0001a8283b156ebd;
d.(2ul) <- u64 0x0005e7a26001c029;
d.(3ul) <- u64 0x000739c663a03cbb;
d.(4ul) <- u64 0x00052036cee2b6ff;
assert_norm (S51.as_nat5 (u64 0x00034dca135978a3, u64 0x0001a8283b156ebd,
u64 0x0005e7a26001c029, u64 0x000739c663a03cbb, u64 0x00052036cee2b6ff) %
Spec.Curve25519.prime == Spec.Ed25519.d);
fmul out d a;
pop_frame()
[@CInline]
let times_2d out a =
push_frame();
let d2 = create 5ul (u64 0) in
d2.(0ul) <- u64 0x00069b9426b2f159;
d2.(1ul) <- u64 0x00035050762add7a;
d2.(2ul) <- u64 0x0003cf44c0038052;
d2.(3ul) <- u64 0x0006738cc7407977;
d2.(4ul) <- u64 0x0002406d9dc56dff;
fmul out d2 a;
assert_norm (S51.as_nat5 (u64 0x00069b9426b2f159, u64 0x00035050762add7a,
u64 0x0003cf44c0038052, u64 0x0006738cc7407977, u64 0x0002406d9dc56dff) %
Spec.Curve25519.prime == 2 `SC.fmul` Spec.Ed25519.d);
pop_frame()
[@CInline]
let fsquare out a =
push_frame();
let tmp = create 5ul (u128 0) in
BN.fsqr out a tmp;
pop_frame()
[@CInline]
let fsquare_times output input count =
push_frame();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output input tmp count;
pop_frame()
[@CInline]
let fsquare_times_inplace output count =
push_frame();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output output tmp count;
pop_frame()
let inverse out a =
push_frame();
let tmp = create 10ul (u128 0) in
Hacl.Curve25519_51.finv out a tmp;
pop_frame()
[@CInline]
let reduce out =
let (o0, o1, o2, o3, o4) = (out.(0ul), out.(1ul), out.(2ul), out.(3ul), out.(4ul)) in
let (f0, f1, f2, f3, f4) = Hacl.Spec.Curve25519.Field51.carry_felem5_full (o0, o1, o2, o3, o4) in
let (f0, f1, f2, f3, f4) = Hacl.Spec.Curve25519.Field51.subtract_p5 (f0, f1, f2, f3, f4) in
Math.Lemmas.small_mod (S51.as_nat5 (f0, f1, f2, f3, f4)) Spec.Curve25519.prime;
make_u64_5 out f0 f1 f2 f3 f4
let load_51 output input =
push_frame ();
let u64s = create 4ul (u64 0) in
let h0 = ST.get () in
uints_from_bytes_le #U64 u64s input;
let h1 = ST.get () in
BSeq.uints_from_bytes_le_nat_lemma #U64 #SEC #4 (as_seq h0 input);
assert (BSeq.nat_from_intseq_le (as_seq h1 u64s) == BSeq.nat_from_bytes_le (as_seq h0 input));
let u64s3 = u64s.(3ul) in
u64s.(3ul) <- u64s3 &. u64 0x7fffffffffffffff;
mod_mask_lemma u64s3 63ul;
assert_norm (0x7fffffffffffffff = pow2 63 - 1);
assert (v (mod_mask #U64 #SEC 63ul) == v (u64 0x7fffffffffffffff));
let h2 = ST.get () in
assert (v (LSeq.index (as_seq h2 u64s) 3) < pow2 63);
Hacl.Spec.Curve25519.Field64.Lemmas.lemma_felem64_mod255 (as_seq h1 u64s);
assert (BSeq.nat_from_intseq_le (as_seq h2 u64s) == BSeq.nat_from_bytes_le (as_seq h0 input) % pow2 255);
output.(0ul) <- u64s.(0ul) &. mask_51;
output.(1ul) <- (u64s.(0ul) >>. 51ul) |. ((u64s.(1ul) &. u64 0x3fffffffff) <<. 13ul);
output.(2ul) <- (u64s.(1ul) >>. 38ul) |. ((u64s.(2ul) &. u64 0x1ffffff) <<. 26ul);
output.(3ul) <- (u64s.(2ul) >>. 25ul) |. ((u64s.(3ul) &. u64 0xfff) <<. 39ul);
output.(4ul) <- u64s.(3ul) >>. 12ul;
SL51.lemma_load_felem (as_seq h2 u64s);
pop_frame () | {
"checked_file": "/",
"dependencies": [
"Spec.Ed25519.fst.checked",
"Spec.Curve25519.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"Lib.ByteBuffer.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Definition.fst.checked",
"Hacl.Spec.Curve25519.Field51.fst.checked",
"Hacl.Impl.Curve25519.Field51.fst.checked",
"Hacl.Curve25519_51.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Hacl.Bignum25519.fst"
} | [
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Curve25519.Field51",
"short_module": "BN"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Lemmas",
"short_module": "SL51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Ed25519.Field51",
"short_module": "F51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
output: Lib.Buffer.lbuffer Lib.IntTypes.uint8 32ul ->
input: Lib.Buffer.lbuffer Lib.IntTypes.uint64 5ul
-> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Lib.Buffer.lbuffer",
"Lib.IntTypes.uint8",
"FStar.UInt32.__uint_to_t",
"Lib.IntTypes.uint64",
"FStar.HyperStack.ST.pop_frame",
"Prims.unit",
"Lib.ByteSequence.uints_to_bytes_le_nat_lemma",
"Lib.IntTypes.U64",
"Lib.IntTypes.SEC",
"Hacl.Impl.Ed25519.Field51.fevalh",
"Lib.ByteBuffer.uints_to_bytes_le",
"Prims._assert",
"Prims.eq2",
"Lib.Sequence.seq",
"Prims.l_or",
"Prims.nat",
"FStar.Seq.Base.length",
"Lib.IntTypes.v",
"Lib.IntTypes.U32",
"Lib.IntTypes.PUB",
"Prims.l_and",
"Lib.Sequence.length",
"Lib.IntTypes.uint_t",
"Prims.b2t",
"Prims.op_LessThan",
"Prims.pow2",
"FStar.Mul.op_Star",
"Lib.IntTypes.bits",
"Lib.ByteSequence.nat_from_intseq_le",
"Lib.Buffer.as_seq",
"Lib.Buffer.MUT",
"Lib.ByteSequence.nat_to_intseq_le",
"FStar.Monotonic.HyperStack.mem",
"FStar.HyperStack.ST.get",
"Hacl.Impl.Curve25519.Field51.store_felem",
"Lib.Buffer.lbuffer_t",
"Lib.IntTypes.int_t",
"FStar.UInt32.uint_to_t",
"FStar.UInt32.t",
"Lib.Buffer.create",
"Lib.IntTypes.u64",
"FStar.HyperStack.ST.push_frame"
] | [] | false | true | false | false | false | let store_51 output input =
| let h0 = ST.get () in
push_frame ();
let u64s = create 4ul (u64 0) in
BN.store_felem u64s input;
let h1 = ST.get () in
assert (as_seq h1 u64s == BSeq.nat_to_intseq_le 4 (F51.fevalh h0 input));
uints_to_bytes_le 4ul output u64s;
BSeq.uints_to_bytes_le_nat_lemma #U64 #SEC 4 (F51.fevalh h0 input);
pop_frame () | false |
Binding.fst | Binding.parser_may_fail | val parser_may_fail (env: env) (t: typ) : ML bool | val parser_may_fail (env: env) (t: typ) : ML bool | let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 16,
"end_line": 256,
"start_col": 0,
"start_line": 250
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> t: Ast.typ -> FStar.All.ML Prims.bool | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.typ",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.typ'",
"Ast.with_meta_t",
"Prims.bool",
"Ast.ident",
"Ast.t_kind",
"Prims.list",
"Ast.either",
"Ast.expr",
"Ast.out_expr",
"Ast.decl",
"GlobalEnv.decl_attributes",
"GlobalEnv.__proj__Mkdecl_attributes__item__may_fail",
"FStar.Pervasives.Native.tuple2",
"GlobalEnv.macro_signature",
"Binding.lookup"
] | [] | false | true | false | false | false | let parser_may_fail (env: env) (t: typ) : ML bool =
| match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false | false |
Binding.fst | Binding.has_reader | val has_reader (_:global_env) (_:ident) : ML bool | val has_reader (_:global_env) (_:ident) : ML bool | let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 285,
"start_col": 0,
"start_line": 282
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: GlobalEnv.global_env -> id: Ast.ident -> FStar.All.ML Prims.bool | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.decl",
"GlobalEnv.decl_attributes",
"GlobalEnv.__proj__Mkdecl_attributes__item__has_reader",
"FStar.Pervasives.Native.option",
"FStar.Pervasives.Native.tuple2",
"Ast.either",
"GlobalEnv.macro_signature",
"Prims.bool",
"Hashtable.try_find",
"Ast.ident'",
"GlobalEnv.__proj__Mkglobal_env__item__ge_h",
"Ast.__proj__Mkwith_meta_t__item__v"
] | [] | false | true | false | false | false | let has_reader (env: global_env) (id: ident) : ML bool =
| match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false | false |
Binding.fst | Binding.parser_kind_nz | val parser_kind_nz (env:global_env) (id:ident) : ML (option bool) | val parser_kind_nz (env:global_env) (id:ident) : ML (option bool) | let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 13,
"end_line": 290,
"start_col": 0,
"start_line": 287
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: GlobalEnv.global_env -> id: Ast.ident
-> FStar.All.ML (FStar.Pervasives.Native.option Prims.bool) | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.decl",
"GlobalEnv.decl_attributes",
"GlobalEnv.__proj__Mkdecl_attributes__item__parser_kind_nz",
"FStar.Pervasives.Native.option",
"FStar.Pervasives.Native.tuple2",
"Ast.either",
"GlobalEnv.macro_signature",
"FStar.Pervasives.Native.None",
"Prims.bool",
"Hashtable.try_find",
"Ast.ident'",
"GlobalEnv.__proj__Mkglobal_env__item__ge_h",
"Ast.__proj__Mkwith_meta_t__item__v"
] | [] | false | true | false | false | false | let parser_kind_nz (env: global_env) (id: ident) : ML (option bool) =
| match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None | false |
Binding.fst | Binding.size_of_integral_typ | val size_of_integral_typ (_:env) (_:typ) (_:range) : ML int | val size_of_integral_typ (_:env) (_:typ) (_:range) : ML int | let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8 | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 22,
"end_line": 367,
"start_col": 0,
"start_line": 355
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> t: Ast.typ -> r: Ast.range -> FStar.All.ML Prims.int | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.typ",
"Ast.range",
"FStar.All.failwith",
"Prims.int",
"FStar.Pervasives.Native.option",
"Ast.integer_type",
"Binding.tag_of_integral_typ",
"Prims.unit",
"Ast.error",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.print_typ",
"Prims.bool",
"Prims.op_Negation",
"Binding.typ_is_integral",
"Binding.unfold_typ_abbrev_and_enum"
] | [] | false | true | false | false | false | let size_of_integral_typ (env: env) (t: typ) r : ML int =
| let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s" (print_typ t)) r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8 | false |
Binding.fst | Binding.parser_weak_kind | val parser_weak_kind (env:global_env) (id:ident) : ML (option weak_kind) | val parser_weak_kind (env:global_env) (id:ident) : ML (option weak_kind) | let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 13,
"end_line": 295,
"start_col": 0,
"start_line": 292
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: GlobalEnv.global_env -> id: Ast.ident
-> FStar.All.ML (FStar.Pervasives.Native.option Ast.weak_kind) | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.decl",
"GlobalEnv.decl_attributes",
"FStar.Pervasives.Native.Some",
"Ast.weak_kind",
"GlobalEnv.__proj__Mkdecl_attributes__item__parser_weak_kind",
"FStar.Pervasives.Native.option",
"FStar.Pervasives.Native.tuple2",
"Ast.either",
"GlobalEnv.macro_signature",
"FStar.Pervasives.Native.None",
"Hashtable.try_find",
"Ast.ident'",
"GlobalEnv.__proj__Mkglobal_env__item__ge_h",
"Ast.__proj__Mkwith_meta_t__item__v"
] | [] | false | true | false | false | false | let parser_weak_kind (env: global_env) (id: ident) : ML (option _) =
| match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None | false |
Binding.fst | Binding.is_strong_prefix_field_array | val is_strong_prefix_field_array (a: field_array_t) : Tot bool | val is_strong_prefix_field_array (a: field_array_t) : Tot bool | let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a) | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 22,
"end_line": 1210,
"start_col": 0,
"start_line": 1209
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf } | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | a: Ast.field_array_t -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Ast.field_array_t",
"Prims.op_Negation",
"Ast.uu___is_FieldScalar",
"Prims.bool"
] | [] | false | false | false | true | false | let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
| not (FieldScalar? a) | false |
Binding.fst | Binding.update_typ_abbrev | val update_typ_abbrev (_:env) (id:ident) (t:typ) : ML unit | val update_typ_abbrev (_:env) (id:ident) (t:typ) : ML unit | let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found" | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 43,
"end_line": 337,
"start_col": 0,
"start_line": 323
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> id: Ast.ident -> t: Ast.typ -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.ident",
"Ast.typ",
"Ast.decl",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"Hashtable.insert",
"Ast.ident'",
"FStar.Pervasives.Native.tuple2",
"GlobalEnv.__proj__Mkglobal_env__item__ge_h",
"Binding.__proj__Mkenv__item__globals",
"Ast.__proj__Mkwith_meta_t__item__v",
"Prims.unit",
"FStar.Pervasives.Native.Mktuple2",
"Ast.Mkdecl",
"Ast.__proj__Mkdecl__item__d_exported",
"Ast.with_meta_t",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Ast.Mkwith_meta_t",
"Ast.TypeAbbrev",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.__proj__Mkwith_meta_t__item__comments",
"FStar.All.failwith",
"FStar.Pervasives.Native.option",
"Hashtable.try_find"
] | [] | false | true | false | false | false | let update_typ_abbrev (env: env) (i: ident) (t: typ) : ML unit =
| match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> { d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = { d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ -> failwith "Type abbreviation not found" | false |
Binding.fst | Binding.add_output_type | val add_output_type (ge: global_env) (i: ident) (d: decl{OutputType? d.d_decl.v}) : ML unit | val add_output_type (ge: global_env) (i: ident) (d: decl{OutputType? d.d_decl.v}) : ML unit | let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 20,
"end_line": 455,
"start_col": 0,
"start_line": 451
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
ge: GlobalEnv.global_env ->
i: Ast.ident ->
d: Ast.decl{OutputType? (Mkwith_meta_t?.v (Mkdecl?.d_decl d))}
-> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.decl",
"Prims.b2t",
"Ast.uu___is_OutputType",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Ast.ident'",
"Prims.unit",
"Ast.__proj__Mktypedef_names__item__typedef_abbrev",
"Ast.__proj__Mkout_typ__item__out_typ_names",
"Ast.__proj__OutputType__item___0",
"Hashtable.insert",
"GlobalEnv.__proj__Mkglobal_env__item__ge_out_t"
] | [] | false | true | false | false | false | let add_output_type (ge: global_env) (i: ident) (d: decl{OutputType? d.d_decl.v}) : ML unit =
| let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v | false |
Binding.fst | Binding.check_mutable_param | val check_mutable_param (env: env) (p: param) : ML unit | val check_mutable_param (env: env) (p: param) : ML unit | let check_mutable_param (env:env) (p:param) : ML unit =
//a mutable parameter should have a pointer type
//and the base type may be a base type or an output type
let t, _, _ = p in
match t.v with
| Pointer bt ->
check_mutable_param_type env bt
| _ ->
error (Printf.sprintf "%s is not a valid mutable parameter type, it is not a pointer type" (print_typ t)) t.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 117,
"end_line": 1617,
"start_col": 0,
"start_line": 1609
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
]
let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None
let rec check_integer_or_output_type (env:env) (t:typ) : ML unit =
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] -> //either it should be a base type, or an output type
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else if not (k = KindOutput) then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> p: Ast.param -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.param",
"Ast.typ",
"Ast.ident",
"Ast.qualifier",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.typ'",
"Ast.with_meta_t",
"Binding.check_mutable_param_type",
"Prims.unit",
"Ast.error",
"Ast.__proj__Mkwith_meta_t__item__range",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.print_typ"
] | [] | false | true | false | false | false | let check_mutable_param (env: env) (p: param) : ML unit =
| let t, _, _ = p in
match t.v with
| Pointer bt -> check_mutable_param_type env bt
| _ ->
error (Printf.sprintf "%s is not a valid mutable parameter type, it is not a pointer type"
(print_typ t))
t.range | false |
Binding.fst | Binding.bit_order_of_integral_typ | val bit_order_of_integral_typ (_:env) (_:typ) (_:range) : ML bitfield_bit_order | val bit_order_of_integral_typ (_:env) (_:typ) (_:range) : ML bitfield_bit_order | let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 28,
"end_line": 378,
"start_col": 0,
"start_line": 369
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8 | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> t: Ast.typ -> r: Ast.range -> FStar.All.ML Ast.bitfield_bit_order | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.typ",
"Ast.range",
"FStar.Pervasives.Native.option",
"Ast.integer_type",
"FStar.All.failwith",
"Ast.bitfield_bit_order",
"FStar.Pervasives.Native.tuple2",
"Prims.l_imp",
"Prims.b2t",
"FStar.Pervasives.Native.uu___is_Some",
"FStar.Pervasives.Native.snd",
"FStar.Pervasives.Native.fst",
"Binding.tag_and_bit_order_of_integral_typ",
"Prims.unit",
"Ast.error",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.print_typ",
"Prims.bool",
"Prims.op_Negation",
"Binding.typ_is_integral",
"Binding.unfold_typ_abbrev_and_enum"
] | [] | false | true | false | false | false | let bit_order_of_integral_typ (env: env) (t: typ) r : ML bitfield_bit_order =
| let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s" (print_typ t)) r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order | false |
Binding.fst | Binding.check_field_t | val check_field_t : Type0 | let check_field_t = env -> field -> ML field | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 44,
"end_line": 1266,
"start_col": 0,
"start_line": 1266
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | Type0 | Prims.Tot | [
"total"
] | [] | [
"Binding.env",
"Ast.field"
] | [] | false | false | false | true | true | let check_field_t =
| env -> field -> ML field | false |
|
Binding.fst | Binding.add_extern_type | val add_extern_type (ge: global_env) (i: ident) (d: decl{ExternType? d.d_decl.v}) : ML unit | val add_extern_type (ge: global_env) (i: ident) (d: decl{ExternType? d.d_decl.v}) : ML unit | let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 20,
"end_line": 466,
"start_col": 0,
"start_line": 462
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
ge: GlobalEnv.global_env ->
i: Ast.ident ->
d: Ast.decl{ExternType? (Mkwith_meta_t?.v (Mkdecl?.d_decl d))}
-> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.decl",
"Prims.b2t",
"Ast.uu___is_ExternType",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Ast.ident'",
"Prims.unit",
"Ast.__proj__Mktypedef_names__item__typedef_abbrev",
"Ast.__proj__ExternType__item___0",
"Hashtable.insert",
"GlobalEnv.__proj__Mkglobal_env__item__ge_extern_t"
] | [] | false | true | false | false | false | let add_extern_type (ge: global_env) (i: ident) (d: decl{ExternType? d.d_decl.v}) : ML unit =
| let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v | false |
Binding.fst | Binding.allowed_base_types_as_output_types | val allowed_base_types_as_output_types : Prims.list Prims.string | let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
] | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 1,
"end_line": 1575,
"start_col": 0,
"start_line": 1570
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | Prims.list Prims.string | Prims.Tot | [
"total"
] | [] | [
"Prims.Cons",
"Prims.string",
"Prims.Nil"
] | [] | false | false | false | true | false | let allowed_base_types_as_output_types =
| [
"UINT8"; "UINT16"; "UINT32"; "UINT64"; "UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE"; "PUINT8";
"Bool"
] | false |
|
Binding.fst | Binding.lookup_extern_fn | val lookup_extern_fn (ge: global_env) (f: ident) : ML (typ & list param) | val lookup_extern_fn (ge: global_env) (f: ident) : ML (typ & list param) | let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 108,
"end_line": 518,
"start_col": 0,
"start_line": 515
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | ge: GlobalEnv.global_env -> f: Ast.ident -> FStar.All.ML (Ast.typ * Prims.list Ast.param) | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.typ",
"Prims.list",
"Ast.param",
"Ast.range",
"Ast.comments",
"Prims.bool",
"FStar.Pervasives.Native.Mktuple2",
"FStar.Pervasives.Native.tuple2",
"FStar.Pervasives.Native.option",
"Ast.decl",
"Ast.error",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.ident'",
"Hashtable.try_find",
"GlobalEnv.__proj__Mkglobal_env__item__ge_extern_fn",
"Ast.__proj__Mkwith_meta_t__item__v"
] | [] | false | true | false | false | false | let lookup_extern_fn (ge: global_env) (f: ident) : ML (typ & list param) =
| match H.try_find ge.ge_extern_fn f.v with
| Some { d_decl = { v = ExternFn _ ret ps } } -> ret, ps
| _ ->
error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f))
f.range | false |
Binding.fst | Binding.add_extern_fn | val add_extern_fn (ge: global_env) (i: ident) (d: decl{ExternFn? d.d_decl.v}) : ML unit | val add_extern_fn (ge: global_env) (i: ident) (d: decl{ExternFn? d.d_decl.v}) : ML unit | let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 32,
"end_line": 483,
"start_col": 0,
"start_line": 482
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
ge: GlobalEnv.global_env ->
i: Ast.ident ->
d: Ast.decl{ExternFn? (Mkwith_meta_t?.v (Mkdecl?.d_decl d))}
-> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.decl",
"Prims.b2t",
"Ast.uu___is_ExternFn",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Hashtable.insert",
"Ast.ident'",
"GlobalEnv.__proj__Mkglobal_env__item__ge_extern_fn",
"Prims.unit"
] | [] | false | true | false | false | false | let add_extern_fn (ge: global_env) (i: ident) (d: decl{ExternFn? d.d_decl.v}) : ML unit =
| H.insert ge.ge_extern_fn i.v d | false |
Binding.fst | Binding.bind_decls | val bind_decls (g:global_env) (p:list decl) : ML (list decl & global_env) | val bind_decls (g:global_env) (p:list decl) : ML (list decl & global_env) | let bind_decls (g:global_env) (p:list decl) : ML (list decl & global_env) =
List.map (bind_decl g) p, g | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 29,
"end_line": 1818,
"start_col": 0,
"start_line": 1817
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
]
let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None
let rec check_integer_or_output_type (env:env) (t:typ) : ML unit =
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] -> //either it should be a base type, or an output type
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else if not (k = KindOutput) then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
let check_mutable_param (env:env) (p:param) : ML unit =
//a mutable parameter should have a pointer type
//and the base type may be a base type or an output type
let t, _, _ = p in
match t.v with
| Pointer bt ->
check_mutable_param_type env bt
| _ ->
error (Printf.sprintf "%s is not a valid mutable parameter type, it is not a pointer type" (print_typ t)) t.range
let check_params (env:env) (ps:list param) : ML unit =
ps |> List.iter (fun (t, p, q) ->
if q = Mutable then check_mutable_param env (t, p, q)
else ignore (check_typ true env t);
add_local env p t)
let elaborate_record_decl (e:global_env)
(tdnames:Ast.typedef_names)
(params:list param)
(where:option expr)
(fields:list field)
(range:range)
(comments:comments)
(is_exported:bool)
: ML decl
= let env = { mk_env e with this=Some tdnames.typedef_name } in
(* Check parameters, that their types are well-formed;
extend the environments with them *)
check_params env params;
(* If a where-clause is present, elaborate it into a refined unit field *)
let where, maybe_unit_field =
match where with
| None ->
None, []
| Some e ->
let e, t = check_expr env e in
if not (eq_typ env t tbool)
then error (Printf.sprintf "Expected a boolean where clause; got %s"
(print_typ t))
e.range;
let w = Some e in
let field =
{ field_dependence = true;
field_ident = with_range (to_ident' "__precondition") e.range;
field_type = tunit;
field_array_opt = FieldScalar;
field_constraint = w;
field_bitwidth = None;
field_action = None;
field_probe = None
}
in
let af = with_range (AtomicField (with_range field e.range)) e.range in
w, [af]
in
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields = check_record check_field env fields in
let fields = maybe_unit_field@fields in
let fields = elaborate_bit_fields env fields in
let d = mk_decl (Record tdnames params where fields) range comments is_exported in
let attrs = {
may_fail = false; //only its fields may fail; not the struct itself
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = weak_kind_of_record env fields;
parser_kind_nz = None
}
in
add_global e tdnames.typedef_name d (Inl attrs);
d
(*
* An output field type is either a base type or another output type
*
* TODO: check field name shadowing
* TODO: check bit fields, do we check that the sum of bitwidths is ok etc.?
* as of now, we don't check anything here
*)
let rec check_output_field (ge:global_env) (fld:out_field) : ML unit =
match fld with
| Out_field_named _ t _bopt -> check_integer_or_output_type (env_of_global_env ge) t
| Out_field_anon l _ -> check_output_fields ge l
and check_output_fields (ge:global_env) (flds:list out_field) : ML unit =
List.iter (check_output_field ge) flds
let bind_decl (e:global_env) (d:decl) : ML decl =
match d.d_decl.v with
| ModuleAbbrev i m -> d
| Define i None c ->
let t = type_of_constant d.d_decl.range c in
let d = decl_with_v d (Define i (Some t) c) in
add_global e i d (Inr (nullary_macro t (Some (with_range (Constant c) d.d_decl.range))));
d
| Define i (Some t) c ->
let env = mk_env e in
let t = check_typ false env t in
let t' = type_of_constant d.d_decl.range c in
let d = decl_with_v d (Define i (Some t) c) in
if eq_typ env t t'
then (add_global e i d (Inr (nullary_macro (type_of_constant d.d_decl.range c)
(Some (with_range (Constant c) d.d_decl.range))));
d)
else error "Ill-typed constant" d.d_decl.range
| TypeAbbrev t i ->
let env = mk_env e in
let t = check_typ false env t in
let wk =
match typ_weak_kind env t with
| None -> failwith (Printf.sprintf "Weak kind not found for type %s" (print_typ t))
| Some wk -> wk
in
let integral, bit_order = tag_and_bit_order_of_integral_typ env t in
let attrs =
{
may_fail = parser_may_fail env t;
integral = integral;
bit_order = bit_order;
has_reader = typ_has_reader env t;
parser_weak_kind = wk;
parser_kind_nz = None
}
in
let d = decl_with_v d (TypeAbbrev t i) in
add_global e i d (Inl attrs);
d
| Enum t i cases ->
let env = mk_env e in
let t = check_typ false env t in
let cases_idents = Desugar.check_desugared_enum_cases cases in
cases_idents |> List.iter (fun i ->
let _, t' = check_expr env (with_dummy_range (Identifier i)) in
if not (eq_typ env t t')
then error (Printf.sprintf "Inconsistent type of enumeration identifier: Expected %s, got %s"
(print_typ t)
(print_typ t'))
d.d_decl.range);
let integral = typ_as_integer_type t in
let bit_order = bit_order_of_typ t in
let attrs =
{
may_fail = true;
integral = Some integral;
bit_order = Some bit_order;
has_reader = false; //it's a refinement, so you can't read it again because of double fetches
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = None
}
in
let d = decl_with_v d (Enum t i cases) in
add_global e i d (Inl attrs);
d
| Record tdnames params where fields ->
elaborate_record_decl e tdnames params where fields d.d_decl.range d.d_decl.comments d.d_exported
| CaseType tdnames params switch ->
let env = { mk_env e with this=Some tdnames.typedef_name } in
check_params env params;
let switch = check_switch check_field env switch in
let wk = weak_kind_of_switch_case env switch in
let attrs = {
may_fail = false;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = wk;
parser_kind_nz = None
} in
let d = mk_decl (CaseType tdnames params switch) d.d_decl.range d.d_decl.comments d.d_exported in
add_global e tdnames.typedef_name d (Inl attrs);
d
| OutputType out_t ->
check_output_fields e out_t.out_typ_fields;
add_output_type e out_t.out_typ_names.typedef_name d;
d
| ExternType tdnames ->
add_extern_type e tdnames.typedef_name d;
d
| ExternFn f ret params ->
let env = mk_env e in
let ret = check_typ true env ret in
check_params env params;
let d = mk_decl (ExternFn f ret params) d.d_decl.range d.d_decl.comments d.d_exported in
add_extern_fn e f d;
d
| ExternProbe i ->
add_extern_probe e i d;
d | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | g: GlobalEnv.global_env -> p: Prims.list Ast.decl
-> FStar.All.ML (Prims.list Ast.decl * GlobalEnv.global_env) | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Prims.list",
"Ast.decl",
"FStar.Pervasives.Native.Mktuple2",
"FStar.Pervasives.Native.tuple2",
"FStar.List.map",
"Binding.bind_decl"
] | [] | false | true | false | false | false | let bind_decls (g: global_env) (p: list decl) : ML (list decl & global_env) =
| List.map (bind_decl g) p, g | false |
Binding.fst | Binding.lookup_output_type | val lookup_output_type (ge: global_env) (i: ident) : ML out_typ | val lookup_output_type (ge: global_env) (i: ident) : ML out_typ | let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 88,
"end_line": 488,
"start_col": 0,
"start_line": 485
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | ge: GlobalEnv.global_env -> i: Ast.ident -> FStar.All.ML Ast.out_typ | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.out_typ",
"Ast.range",
"Ast.comments",
"Prims.bool",
"FStar.Pervasives.Native.option",
"Ast.decl",
"Ast.error",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.ident'",
"Hashtable.try_find",
"GlobalEnv.__proj__Mkglobal_env__item__ge_out_t",
"Ast.__proj__Mkwith_meta_t__item__v"
] | [] | false | true | false | false | false | let lookup_output_type (ge: global_env) (i: ident) : ML out_typ =
| match H.try_find ge.ge_out_t i.v with
| Some { d_decl = { v = OutputType out_t } } -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range | false |
Binding.fst | Binding.lookup_extern_type | val lookup_extern_type (ge: global_env) (i: ident) : ML unit | val lookup_extern_type (ge: global_env) (i: ident) : ML unit | let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 104,
"end_line": 513,
"start_col": 0,
"start_line": 510
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | ge: GlobalEnv.global_env -> i: Ast.ident -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.typedef_names",
"Ast.range",
"Ast.comments",
"Prims.bool",
"Prims.unit",
"FStar.Pervasives.Native.option",
"Ast.decl",
"Ast.error",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.ident'",
"Hashtable.try_find",
"GlobalEnv.__proj__Mkglobal_env__item__ge_extern_t",
"Ast.__proj__Mkwith_meta_t__item__v"
] | [] | false | true | false | false | false | let lookup_extern_type (ge: global_env) (i: ident) : ML unit =
| match H.try_find ge.ge_extern_t i.v with
| Some { d_decl = { v = ExternType _ } } -> ()
| _ ->
error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range | false |
Binding.fst | Binding.add_extern_probe | val add_extern_probe (ge: global_env) (i: ident) (d: decl{ExternProbe? d.d_decl.v}) : ML unit | val add_extern_probe (ge: global_env) (i: ident) (d: decl{ExternProbe? d.d_decl.v}) : ML unit | let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 31,
"end_line": 474,
"start_col": 0,
"start_line": 473
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
ge: GlobalEnv.global_env ->
i: Ast.ident ->
d: Ast.decl{ExternProbe? (Mkwith_meta_t?.v (Mkdecl?.d_decl d))}
-> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.decl",
"Prims.b2t",
"Ast.uu___is_ExternProbe",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Hashtable.insert",
"Ast.ident'",
"GlobalEnv.__proj__Mkglobal_env__item__ge_probe_fn",
"Prims.unit"
] | [] | false | true | false | false | false | let add_extern_probe (ge: global_env) (i: ident) (d: decl{ExternProbe? d.d_decl.v}) : ML unit =
| H.insert ge.ge_probe_fn i.v d | false |
Spec.Matrix.fst | Spec.Matrix.elem | val elem : Type0 | let elem = uint16 | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 17,
"end_line": 80,
"start_col": 0,
"start_line": 80
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | Type0 | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.uint16"
] | [] | false | false | false | true | true | let elem =
| uint16 | false |
|
Binding.fst | Binding.range_of_typ_param | val range_of_typ_param : p: Ast.typ_param -> Ast.range | let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 34,
"end_line": 622,
"start_col": 0,
"start_line": 620
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | p: Ast.typ_param -> Ast.range | Prims.Tot | [
"total"
] | [] | [
"Ast.typ_param",
"Ast.expr",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.expr'",
"Ast.out_expr",
"Ast.out_expr'",
"Ast.__proj__Mkout_expr__item__out_expr_node",
"Ast.range"
] | [] | false | false | false | true | false | let range_of_typ_param (p: typ_param) =
| match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range | false |
|
Binding.fst | Binding.lookup_output_type_field | val lookup_output_type_field (ge: global_env) (i f: ident) : ML (typ & option int) | val lookup_output_type_field (ge: global_env) (i f: ident) : ML (typ & option int) | let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 107,
"end_line": 508,
"start_col": 0,
"start_line": 493
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | ge: GlobalEnv.global_env -> i: Ast.ident -> f: Ast.ident
-> FStar.All.ML (Ast.typ * FStar.Pervasives.Native.option Prims.int) | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.ident",
"Ast.__proj__Mkout_typ__item__out_typ_fields",
"FStar.Pervasives.Native.tuple2",
"Ast.typ",
"FStar.Pervasives.Native.option",
"Prims.int",
"Ast.error",
"FStar.Printf.sprintf",
"Ast.ident_to_string",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.ident'",
"Prims.list",
"Ast.out_field",
"FStar.Pervasives.Native.None",
"Ast.eq_idents",
"FStar.Pervasives.Native.Some",
"FStar.Pervasives.Native.Mktuple2",
"Prims.bool",
"Ast.out_typ",
"Binding.lookup_output_type"
] | [] | false | true | false | false | false | let lookup_output_type_field (ge: global_env) (i f: ident) : ML (typ & option int) =
| let out_t = lookup_output_type ge i in
let rec find (flds: list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| Out_field_named f' t n :: tl -> if eq_idents f f' then Some (t, n) else find tl
| Out_field_anon l _ :: tl ->
(match find l with
| None -> find tl
| Some t -> Some t)
in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f))
f.range | false |
Spec.Matrix.fst | Spec.Matrix.op_Array_Access | val op_Array_Access : m: Spec.Matrix.matrix n1 n2 ->
_: (i: Lib.IntTypes.size_nat{i < n1} * j: Lib.IntTypes.size_nat{j < n2})
-> Spec.Matrix.elem | let op_Array_Access #n1 #n2 (m:matrix n1 n2) (i,j) = mget m i j | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 63,
"end_line": 103,
"start_col": 0,
"start_line": 103
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2)
val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2
let create n1 n2 = LSeq.create (n1 * n2) (u16 0)
val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem
let mget #n1 #n2 a i j =
index_lt n1 n2 i j;
a.[i * n2 + j] | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
m: Spec.Matrix.matrix n1 n2 ->
_: (i: Lib.IntTypes.size_nat{i < n1} * j: Lib.IntTypes.size_nat{j < n2})
-> Spec.Matrix.elem | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Spec.Matrix.matrix",
"FStar.Pervasives.Native.tuple2",
"Prims.op_LessThan",
"Spec.Matrix.mget",
"Spec.Matrix.elem"
] | [] | false | false | false | false | false | let ( .() ) #n1 #n2 (m: matrix n1 n2) (i, j) =
| mget m i j | false |
|
Binding.fst | Binding.weak_kind_of_list | val weak_kind_of_list (wa: ('a -> ML weak_kind)) (xs: list 'a) : ML weak_kind | val weak_kind_of_list (wa: ('a -> ML weak_kind)) (xs: list 'a) : ML weak_kind | let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 15,
"end_line": 1232,
"start_col": 0,
"start_line": 1219
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type)) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | wa: (_: 'a -> FStar.All.ML Ast.weak_kind) -> xs: Prims.list 'a -> FStar.All.ML Ast.weak_kind | FStar.All.ML | [
"ml"
] | [] | [
"Ast.weak_kind",
"Prims.list",
"Ast.WeakKindWeak",
"FStar.Pervasives.Native.option",
"FStar.List.fold_left",
"FStar.Pervasives.Native.Some",
"Ast.weak_kind_glb",
"FStar.Pervasives.Native.None"
] | [] | false | true | false | false | false | let weak_kind_of_list (wa: ('a -> ML weak_kind)) (xs: list 'a) : ML weak_kind =
| let k =
List.fold_left (fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k | false |
Binding.fst | Binding.check_out_expr | val check_out_expr (env: env) (oe0: out_expr) : ML (oe: out_expr{Some? oe.out_expr_meta}) | val check_out_expr (env: env) (oe0: out_expr) : ML (oe: out_expr{Some? oe.out_expr_meta}) | let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range) | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 56,
"end_line": 618,
"start_col": 0,
"start_line": 532
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> oe0: Ast.out_expr
-> FStar.All.ML (oe: Ast.out_expr{Some? (Mkout_expr?.out_expr_meta oe)}) | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.out_expr",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.out_expr'",
"Ast.__proj__Mkout_expr__item__out_expr_node",
"Ast.ident",
"Ast.Mkout_expr",
"FStar.Pervasives.Native.Some",
"Ast.out_expr_meta_t",
"Ast.Mkout_expr_meta_t",
"FStar.Pervasives.Native.None",
"Prims.int",
"Prims.b2t",
"FStar.Pervasives.Native.uu___is_Some",
"Ast.__proj__Mkout_expr__item__out_expr_meta",
"Ast.typ",
"Binding.lookup_expr_name",
"Ast.with_meta_t",
"Ast.typ'",
"FStar.Pervasives.Native.option",
"FStar.Pervasives.Native.Mktuple2",
"Ast.Mkwith_meta_t",
"Ast.OE_star",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.__proj__Mkwith_meta_t__item__comments",
"FStar.Pervasives.Native.tuple2",
"Ast.error",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.print_out_expr",
"Ast.print_typ",
"FStar.Pervasives.Native.__proj__Some__item__v",
"Binding.check_out_expr",
"Ast.OE_addrof",
"Ast.with_range",
"Ast.Pointer",
"Ast.OE_deref",
"Binding.lookup_output_type_field",
"GlobalEnv.global_env",
"Binding.global_env_of_env",
"Binding.check_output_type",
"Ast.OE_dot"
] | [
"recursion"
] | false | true | false | false | false | let rec check_out_expr (env: env) (oe0: out_expr) : ML (oe: out_expr{Some? oe.out_expr_meta}) =
| match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{
oe0 with
out_expr_meta = Some ({ out_expr_base_t = t; out_expr_t = t; out_expr_bit_width = None })
}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt ; out_expr_t = oe_t ; out_expr_bit_width = bopt } =
Some?.v oe.out_expr_meta
in
(match oe_t.v, bopt with
| Pointer t, None ->
{
oe0 with
out_expr_node = { oe0.out_expr_node with v = OE_star oe };
out_expr_meta
=
Some ({ out_expr_base_t = oe_bt; out_expr_t = t; out_expr_bit_width = None })
}
| _ ->
error (Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0)
(print_typ oe_t))
oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt ; out_expr_t = oe_t ; out_expr_bit_width = bopt } =
Some?.v oe.out_expr_meta
in
(match bopt with
| None ->
{
oe0 with
out_expr_node = { oe0.out_expr_node with v = OE_addrof oe };
out_expr_meta
=
Some
({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None
})
}
| _ ->
error (Printf.sprintf "Cannot take address of a bit field %s" (print_out_expr oe0))
oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt ; out_expr_t = oe_t ; out_expr_bit_width = bopt } =
Some?.v oe.out_expr_meta
in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field (global_env_of_env env) i f in
{
oe0 with
out_expr_node = { oe0.out_expr_node with v = OE_deref oe f };
out_expr_meta
=
Some
({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width
})
}
| _ ->
error (Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0)
(print_typ oe_t))
oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt ; out_expr_t = oe_t ; out_expr_bit_width = bopt } =
Some?.v oe.out_expr_meta
in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field (global_env_of_env env) i f in
{
oe0 with
out_expr_node = { oe0.out_expr_node with v = OE_dot oe f };
out_expr_meta
=
Some
({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width
})
}
| _ ->
error (Printf.sprintf "Cannot take address of a bit field %s" (print_out_expr oe0))
oe.out_expr_node.range) | false |
Spec.Matrix.fst | Spec.Matrix.op_Array_Assignment | val op_Array_Assignment : m: Spec.Matrix.matrix n1 n2 ->
_: (i: Lib.IntTypes.size_nat{i < n1} * j: Lib.IntTypes.size_nat{j < n2}) ->
x: Spec.Matrix.elem
-> Spec.Matrix.matrix n1 n2 | let op_Array_Assignment #n1 #n2 (m:matrix n1 n2) (i,j) x = mset m i j x | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 71,
"end_line": 125,
"start_col": 0,
"start_line": 125
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2)
val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2
let create n1 n2 = LSeq.create (n1 * n2) (u16 0)
val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem
let mget #n1 #n2 a i j =
index_lt n1 n2 i j;
a.[i * n2 + j]
unfold
let op_Array_Access #n1 #n2 (m:matrix n1 n2) (i,j) = mget m i j
val mset:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> v:elem
-> Pure (matrix n1 n2)
(requires True)
(ensures fun r ->
r.(i,j) == v /\ (forall i' j'. (i', j') <> (i, j) ==> r.(i', j') == a.(i',j')))
let mset #n1 #n2 a i j v =
Classical.forall_intro_2 (index_neq #n1 #n2 i j);
index_lt n1 n2 i j;
a.[i * n2 + j] <- v | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
m: Spec.Matrix.matrix n1 n2 ->
_: (i: Lib.IntTypes.size_nat{i < n1} * j: Lib.IntTypes.size_nat{j < n2}) ->
x: Spec.Matrix.elem
-> Spec.Matrix.matrix n1 n2 | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Spec.Matrix.matrix",
"FStar.Pervasives.Native.tuple2",
"Prims.op_LessThan",
"Spec.Matrix.elem",
"Spec.Matrix.mset"
] | [] | false | false | false | false | false | let ( .()<- ) #n1 #n2 (m: matrix n1 n2) (i, j) x =
| mset m i j x | false |
|
Binding.fst | Binding.name_of_field | val name_of_field (f: field) : ident | val name_of_field (f: field) : ident | let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 30,
"end_line": 1423,
"start_col": 0,
"start_line": 1419
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | f: Ast.field -> Ast.ident | Prims.Tot | [
"total"
] | [] | [
"Ast.field",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.field'",
"Ast.with_meta_t",
"Ast.atomic_field'",
"Ast.__proj__Mkatomic_field'__item__field_ident",
"Prims.list",
"Ast.ident",
"FStar.Pervasives.Native.tuple2",
"Ast.expr",
"Ast.case"
] | [] | false | false | false | true | false | let name_of_field (f: field) : ident =
| match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i | SwitchCaseField _ i -> i | false |
Binding.fst | Binding.weak_kind_of_field | val weak_kind_of_field (env: env) (f: field) : ML weak_kind | val weak_kind_of_field (env: env) (f: field) : ML weak_kind | let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 40,
"end_line": 1262,
"start_col": 0,
"start_line": 1234
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> f: Ast.field -> FStar.All.ML Ast.weak_kind | FStar.All.ML | [
"ml"
] | [
"weak_kind_of_field",
"weak_kind_of_record",
"weak_kind_of_switch_case",
"weak_kind_of_case"
] | [
"Binding.env",
"Ast.field",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.field'",
"Ast.with_meta_t",
"Ast.atomic_field'",
"Binding.weak_kind_of_atomic_field",
"Ast.weak_kind",
"Prims.list",
"Ast.ident",
"Binding.weak_kind_of_record",
"FStar.Pervasives.Native.tuple2",
"Ast.expr",
"Ast.case",
"Binding.weak_kind_of_switch_case"
] | [
"mutual recursion"
] | false | true | false | false | false | let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
| match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f | false |
Binding.fst | Binding.check_field_names_unique | val check_field_names_unique (f: list field) : ML unit | val check_field_names_unique (f: list field) : ML unit | let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 80,
"end_line": 1434,
"start_col": 0,
"start_line": 1425
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | f: Prims.list Ast.field -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"Prims.list",
"Ast.field",
"Prims.unit",
"Prims.bool",
"Ast.error",
"FStar.Printf.sprintf",
"Ast.__proj__Mkident'__item__name",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.ident'",
"Ast.__proj__Mkwith_meta_t__item__range",
"FStar.List.for_all",
"Prims.op_Negation",
"Ast.eq_idents",
"Binding.name_of_field",
"Ast.ident"
] | [] | false | true | false | false | false | let check_field_names_unique (f: list field) : ML unit =
| match f with
| [] | [_] -> ()
| hd :: tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range | false |
Binding.fst | Binding.check_record | val check_record (check_field: check_field_t) (env: env) (fs: record) : ML record | val check_record (check_field: check_field_t) (env: env) (fs: record) : ML record | let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 10,
"end_line": 1416,
"start_col": 0,
"start_line": 1364
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | check_field: Binding.check_field_t -> env: Binding.env -> fs: Ast.record -> FStar.All.ML Ast.record | FStar.All.ML | [
"ml"
] | [] | [
"Binding.check_field_t",
"Binding.env",
"Ast.record",
"Prims.list",
"Ast.with_meta_t",
"Ast.field'",
"FStar.List.mapi",
"Prims.int",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.ident",
"FStar.Pervasives.Native.tuple2",
"Ast.expr",
"Ast.case",
"Ast.atomic_field'",
"Prims.op_AmpAmp",
"Ast.__proj__Mkatomic_field'__item__field_dependence",
"Prims.op_Negation",
"Ast.error",
"Ast.__proj__Mkwith_meta_t__item__range",
"Prims.bool",
"Ast.Mkwith_meta_t",
"Ast.AtomicField",
"Ast.__proj__Mkwith_meta_t__item__comments",
"Binding.is_enum",
"Ast.__proj__Mkatomic_field'__item__field_type",
"Binding.typ_has_reader",
"Ast.with_range_and_comments",
"Ast.Mkatomic_field'",
"Ast.__proj__Mkatomic_field'__item__field_ident",
"Ast.__proj__Mkatomic_field'__item__field_array_opt",
"Ast.__proj__Mkatomic_field'__item__field_constraint",
"Ast.__proj__Mkatomic_field'__item__field_bitwidth",
"Ast.__proj__Mkatomic_field'__item__field_action",
"Ast.__proj__Mkatomic_field'__item__field_probe",
"Prims.op_BarBar",
"FStar.Pervasives.Native.uu___is_Some",
"Prims.op_Equality",
"Prims.op_Subtraction",
"Binding.is_used",
"Prims.nat",
"FStar.List.Tot.Base.length",
"FStar.List.map",
"Ast.atomic_field",
"Binding.check_atomic_field",
"Ast.RecordField",
"Binding.check_record",
"Ast.SwitchCaseField",
"Ast.switch_case",
"Binding.check_switch",
"Binding.copy_env"
] | [
"recursion"
] | false | true | false | false | false | let rec check_record (check_field: check_field_t) (env: env) (fs: record) : ML record =
| let env = copy_env env in
let fields =
List.map (fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{ f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i })
fs
in
let nfields = List.length fields in
let fields =
fields |>
List.mapi (fun i f ->
match f.v with
| RecordField _ _ | SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments ({ sf with field_dependence = dependent }) af.range af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence && not has_reader && not is_enum
then
error "The type of this field does not have a reader, either because its values are too large or because reading it may incur a double fetch; subsequent fields cannot depend on it"
af.range
else { f with v = AtomicField af })
in
fields | false |
Binding.fst | Binding.check_mutable_param_type | val check_mutable_param_type (env: env) (t: typ) : ML unit | val check_mutable_param_type (env: env) (t: typ) : ML unit | let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 17,
"end_line": 1597,
"start_col": 0,
"start_line": 1577
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
] | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> t: Ast.typ -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.typ",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.typ'",
"Ast.ident",
"Ast.t_kind",
"Prims.op_BarBar",
"Prims.op_Equality",
"Ast.KindOutput",
"Ast.KindExtern",
"Prims.op_AmpAmp",
"FStar.Pervasives.Native.option",
"Prims.string",
"Ast.__proj__Mkident'__item__modul_name",
"Ast.ident'",
"FStar.Pervasives.Native.None",
"FStar.List.Tot.Base.mem",
"Ast.__proj__Mkident'__item__name",
"Binding.allowed_base_types_as_output_types",
"Prims.unit",
"Prims.bool",
"FStar.Pervasives.Native.Some",
"Ast.with_meta_t",
"Binding.check_mutable_param_type",
"Binding.unfold_typ_abbrev_only",
"Ast.error",
"Ast.__proj__Mkwith_meta_t__item__range",
"FStar.Printf.sprintf",
"Ast.print_typ",
"Ast.decl",
"Ast.print_decl",
"Hashtable.try_find",
"GlobalEnv.__proj__Mkglobal_env__item__ge_out_t",
"Binding.__proj__Mkenv__item__globals"
] | [
"recursion"
] | false | true | false | false | false | let rec check_mutable_param_type (env: env) (t: typ) : ML unit =
| let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d -> Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)"
(print_typ t)
otype)
t.range
in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if
k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None | false |
Binding.fst | Binding.is_bound_locally | val is_bound_locally : env: Binding.env -> i: Ast.ident -> FStar.All.ALL Prims.bool | let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 18,
"end_line": 1362,
"start_col": 0,
"start_line": 1359
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> i: Ast.ident -> FStar.All.ALL Prims.bool | FStar.All.ALL | [] | [] | [
"Binding.env",
"Ast.ident",
"FStar.Pervasives.Native.tuple3",
"Ast.ident'",
"Ast.typ",
"Prims.bool",
"FStar.Pervasives.Native.option",
"Hashtable.try_find",
"Binding.__proj__Mkenv__item__locals",
"Ast.__proj__Mkwith_meta_t__item__v"
] | [] | false | true | false | false | false | let is_bound_locally (env: env) (i: ident) =
| match H.try_find env.locals i.v with
| None -> false
| Some _ -> true | false |
|
Binding.fst | Binding.check_field | val check_field (env: env) (f: field) : ML field | val check_field (env: env) (f: field) : ML field | let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i } | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 73,
"end_line": 1447,
"start_col": 0,
"start_line": 1436
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> f: Ast.field -> FStar.All.ML Ast.field | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.field",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.field'",
"Ast.with_meta_t",
"Ast.atomic_field'",
"Ast.Mkwith_meta_t",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.__proj__Mkwith_meta_t__item__comments",
"Ast.AtomicField",
"Binding.check_atomic_field",
"Ast.atomic_field",
"Prims.list",
"Ast.ident",
"Ast.RecordField",
"Binding.check_record",
"Binding.check_field",
"Ast.record",
"Prims.unit",
"Binding.check_field_names_unique",
"FStar.Pervasives.Native.tuple2",
"Ast.expr",
"Ast.case",
"Ast.SwitchCaseField",
"Binding.check_switch",
"Ast.switch_case"
] | [
"recursion"
] | false | true | false | false | false | let rec check_field (env: env) (f: field) : ML field =
| match f.v with
| AtomicField af -> { f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i -> { f with v = SwitchCaseField (check_switch check_field env swc) i } | false |
Binding.fst | Binding.check_params | val check_params (env: env) (ps: list param) : ML unit | val check_params (env: env) (ps: list param) : ML unit | let check_params (env:env) (ps:list param) : ML unit =
ps |> List.iter (fun (t, p, q) ->
if q = Mutable then check_mutable_param env (t, p, q)
else ignore (check_typ true env t);
add_local env p t) | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 26,
"end_line": 1623,
"start_col": 0,
"start_line": 1619
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
]
let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None
let rec check_integer_or_output_type (env:env) (t:typ) : ML unit =
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] -> //either it should be a base type, or an output type
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else if not (k = KindOutput) then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
let check_mutable_param (env:env) (p:param) : ML unit =
//a mutable parameter should have a pointer type
//and the base type may be a base type or an output type
let t, _, _ = p in
match t.v with
| Pointer bt ->
check_mutable_param_type env bt
| _ ->
error (Printf.sprintf "%s is not a valid mutable parameter type, it is not a pointer type" (print_typ t)) t.range | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> ps: Prims.list Ast.param -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Prims.list",
"Ast.param",
"FStar.List.iter",
"FStar.Pervasives.Native.tuple3",
"Ast.typ",
"Ast.ident",
"Ast.qualifier",
"Binding.add_local",
"Prims.unit",
"Prims.op_Equality",
"Ast.Mutable",
"Binding.check_mutable_param",
"FStar.Pervasives.Native.Mktuple3",
"Prims.bool",
"FStar.Pervasives.ignore",
"Binding.check_typ"
] | [] | false | true | false | false | false | let check_params (env: env) (ps: list param) : ML unit =
| ps |>
List.iter (fun (t, p, q) ->
if q = Mutable then check_mutable_param env (t, p, q) else ignore (check_typ true env t);
add_local env p t) | false |
Binding.fst | Binding.get_exported_decls | val get_exported_decls (ge:global_env) (mname:string) : ML (list ident' & list ident') | val get_exported_decls (ge:global_env) (mname:string) : ML (list ident' & list ident') | let get_exported_decls ge mname =
H.fold (fun k (d, _) (exported_decls, private_decls) ->
if not (k.modul_name = Some mname)
then exported_decls, private_decls
else if d.d_exported
then k::exported_decls, private_decls
else exported_decls, k::private_decls) ge.ge_h ([], []) | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 64,
"end_line": 2027,
"start_col": 0,
"start_line": 2021
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
]
let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None
let rec check_integer_or_output_type (env:env) (t:typ) : ML unit =
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] -> //either it should be a base type, or an output type
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else if not (k = KindOutput) then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
let check_mutable_param (env:env) (p:param) : ML unit =
//a mutable parameter should have a pointer type
//and the base type may be a base type or an output type
let t, _, _ = p in
match t.v with
| Pointer bt ->
check_mutable_param_type env bt
| _ ->
error (Printf.sprintf "%s is not a valid mutable parameter type, it is not a pointer type" (print_typ t)) t.range
let check_params (env:env) (ps:list param) : ML unit =
ps |> List.iter (fun (t, p, q) ->
if q = Mutable then check_mutable_param env (t, p, q)
else ignore (check_typ true env t);
add_local env p t)
let elaborate_record_decl (e:global_env)
(tdnames:Ast.typedef_names)
(params:list param)
(where:option expr)
(fields:list field)
(range:range)
(comments:comments)
(is_exported:bool)
: ML decl
= let env = { mk_env e with this=Some tdnames.typedef_name } in
(* Check parameters, that their types are well-formed;
extend the environments with them *)
check_params env params;
(* If a where-clause is present, elaborate it into a refined unit field *)
let where, maybe_unit_field =
match where with
| None ->
None, []
| Some e ->
let e, t = check_expr env e in
if not (eq_typ env t tbool)
then error (Printf.sprintf "Expected a boolean where clause; got %s"
(print_typ t))
e.range;
let w = Some e in
let field =
{ field_dependence = true;
field_ident = with_range (to_ident' "__precondition") e.range;
field_type = tunit;
field_array_opt = FieldScalar;
field_constraint = w;
field_bitwidth = None;
field_action = None;
field_probe = None
}
in
let af = with_range (AtomicField (with_range field e.range)) e.range in
w, [af]
in
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields = check_record check_field env fields in
let fields = maybe_unit_field@fields in
let fields = elaborate_bit_fields env fields in
let d = mk_decl (Record tdnames params where fields) range comments is_exported in
let attrs = {
may_fail = false; //only its fields may fail; not the struct itself
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = weak_kind_of_record env fields;
parser_kind_nz = None
}
in
add_global e tdnames.typedef_name d (Inl attrs);
d
(*
* An output field type is either a base type or another output type
*
* TODO: check field name shadowing
* TODO: check bit fields, do we check that the sum of bitwidths is ok etc.?
* as of now, we don't check anything here
*)
let rec check_output_field (ge:global_env) (fld:out_field) : ML unit =
match fld with
| Out_field_named _ t _bopt -> check_integer_or_output_type (env_of_global_env ge) t
| Out_field_anon l _ -> check_output_fields ge l
and check_output_fields (ge:global_env) (flds:list out_field) : ML unit =
List.iter (check_output_field ge) flds
let bind_decl (e:global_env) (d:decl) : ML decl =
match d.d_decl.v with
| ModuleAbbrev i m -> d
| Define i None c ->
let t = type_of_constant d.d_decl.range c in
let d = decl_with_v d (Define i (Some t) c) in
add_global e i d (Inr (nullary_macro t (Some (with_range (Constant c) d.d_decl.range))));
d
| Define i (Some t) c ->
let env = mk_env e in
let t = check_typ false env t in
let t' = type_of_constant d.d_decl.range c in
let d = decl_with_v d (Define i (Some t) c) in
if eq_typ env t t'
then (add_global e i d (Inr (nullary_macro (type_of_constant d.d_decl.range c)
(Some (with_range (Constant c) d.d_decl.range))));
d)
else error "Ill-typed constant" d.d_decl.range
| TypeAbbrev t i ->
let env = mk_env e in
let t = check_typ false env t in
let wk =
match typ_weak_kind env t with
| None -> failwith (Printf.sprintf "Weak kind not found for type %s" (print_typ t))
| Some wk -> wk
in
let integral, bit_order = tag_and_bit_order_of_integral_typ env t in
let attrs =
{
may_fail = parser_may_fail env t;
integral = integral;
bit_order = bit_order;
has_reader = typ_has_reader env t;
parser_weak_kind = wk;
parser_kind_nz = None
}
in
let d = decl_with_v d (TypeAbbrev t i) in
add_global e i d (Inl attrs);
d
| Enum t i cases ->
let env = mk_env e in
let t = check_typ false env t in
let cases_idents = Desugar.check_desugared_enum_cases cases in
cases_idents |> List.iter (fun i ->
let _, t' = check_expr env (with_dummy_range (Identifier i)) in
if not (eq_typ env t t')
then error (Printf.sprintf "Inconsistent type of enumeration identifier: Expected %s, got %s"
(print_typ t)
(print_typ t'))
d.d_decl.range);
let integral = typ_as_integer_type t in
let bit_order = bit_order_of_typ t in
let attrs =
{
may_fail = true;
integral = Some integral;
bit_order = Some bit_order;
has_reader = false; //it's a refinement, so you can't read it again because of double fetches
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = None
}
in
let d = decl_with_v d (Enum t i cases) in
add_global e i d (Inl attrs);
d
| Record tdnames params where fields ->
elaborate_record_decl e tdnames params where fields d.d_decl.range d.d_decl.comments d.d_exported
| CaseType tdnames params switch ->
let env = { mk_env e with this=Some tdnames.typedef_name } in
check_params env params;
let switch = check_switch check_field env switch in
let wk = weak_kind_of_switch_case env switch in
let attrs = {
may_fail = false;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = wk;
parser_kind_nz = None
} in
let d = mk_decl (CaseType tdnames params switch) d.d_decl.range d.d_decl.comments d.d_exported in
add_global e tdnames.typedef_name d (Inl attrs);
d
| OutputType out_t ->
check_output_fields e out_t.out_typ_fields;
add_output_type e out_t.out_typ_names.typedef_name d;
d
| ExternType tdnames ->
add_extern_type e tdnames.typedef_name d;
d
| ExternFn f ret params ->
let env = mk_env e in
let ret = check_typ true env ret in
check_params env params;
let d = mk_decl (ExternFn f ret params) d.d_decl.range d.d_decl.comments d.d_exported in
add_extern_fn e f d;
d
| ExternProbe i ->
add_extern_probe e i d;
d
let bind_decls (g:global_env) (p:list decl) : ML (list decl & global_env) =
List.map (bind_decl g) p, g
let initial_global_env () =
let cfg = Deps.get_config () in
let e =
{
ge_h = H.create 10;
ge_out_t = H.create 10;
ge_extern_t = H.create 10;
ge_extern_fn = H.create 10;
ge_probe_fn = H.create 10;
ge_cfg = cfg
}
in
let nullary_decl i =
let td_name =
{ typedef_name = i; typedef_abbrev = i; typedef_ptr_abbrev = i; typedef_attributes = [] }
in
mk_decl (Record td_name [] None []) dummy_range [] true
in
let _type_names =
[
("unit",
{
may_fail = false;
integral = None;
bit_order = None;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some false
});
("Bool",
{
may_fail = true;
integral = None;
bit_order = None;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT8",
{
may_fail = true;
integral = Some UInt8;
bit_order = Some LSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT16",
{
may_fail = true;
integral = Some UInt16;
bit_order = Some LSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT32",
{
may_fail = true;
integral = Some UInt32;
bit_order = Some LSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT64",
{
may_fail = true;
integral = Some UInt64;
bit_order = Some LSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT8BE",
{
may_fail = true;
integral = Some UInt8;
bit_order = Some MSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT16BE",
{
may_fail = true;
integral = Some UInt16;
bit_order = Some MSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT32BE",
{
may_fail = true;
integral = Some UInt32;
bit_order = Some MSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT64BE",
{
may_fail = true;
integral = Some UInt64;
bit_order = Some MSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("field_id",
{
may_fail = true;
integral = Some UInt32;
bit_order = None;
has_reader = false;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("all_bytes",
{
may_fail = false;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = WeakKindConsumesAll;
parser_kind_nz = Some false
});
("all_zeros",
{
may_fail = true;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = WeakKindConsumesAll;
parser_kind_nz = Some false
});
("PUINT8",
{
may_fail = true;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("EVERPARSE_COPY_BUFFER_T",
{
may_fail = true;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
] |>
List.iter (fun (i, attrs) ->
let i = with_dummy_range (to_ident' i) in
add_global e i (nullary_decl i) (Inl attrs))
in
let _operators =
[
("is_range_okay",
{
macro_arguments_t = [tuint32; tuint32; tuint32];
macro_result_t = tbool;
macro_defn_t = None
})
] |>
List.iter (fun (i, d) ->
let i = with_dummy_range (to_ident' i) in
add_global e i (nullary_decl i) (Inr d))
in
let _void =
let void_ident = with_dummy_range (to_ident' "void") in
add_extern_type e
void_ident
(mk_decl (ExternType
({
typedef_name = void_ident;
typedef_abbrev = void_ident;
typedef_ptr_abbrev = void_ident;
typedef_attributes = []
}))
dummy_range
[]
false)
in
let _ =
match cfg with
| None -> ()
| Some (cfg, module_name) ->
List.iter (fun flag ->
let ms = nullary_macro tbool None in
let i = with_dummy_range ({ to_ident' flag with modul_name = Some module_name }) in
let d = mk_decl (ExternFn i tbool []) dummy_range [] false in
add_global e i d (Inr ms))
cfg.compile_time_flags.flags
in
e | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | ge: GlobalEnv.global_env -> mname: Prims.string
-> FStar.All.ML (Prims.list Ast.ident' * Prims.list Ast.ident') | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Prims.string",
"Hashtable.fold",
"FStar.Pervasives.Native.tuple2",
"Prims.list",
"Ast.ident'",
"Ast.decl",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"FStar.Pervasives.Native.Mktuple2",
"Prims.op_Negation",
"Prims.op_Equality",
"FStar.Pervasives.Native.option",
"Ast.__proj__Mkident'__item__modul_name",
"FStar.Pervasives.Native.Some",
"Prims.bool",
"Ast.__proj__Mkdecl__item__d_exported",
"Prims.Cons",
"GlobalEnv.__proj__Mkglobal_env__item__ge_h",
"Prims.Nil"
] | [] | false | true | false | false | false | let get_exported_decls ge mname =
| H.fold (fun k (d, _) (exported_decls, private_decls) ->
if not (k.modul_name = Some mname)
then exported_decls, private_decls
else
if d.d_exported
then k :: exported_decls, private_decls
else exported_decls, k :: private_decls)
ge.ge_h
([], []) | false |
Binding.fst | Binding.check_output_fields | val check_output_fields (ge: global_env) (flds: list out_field) : ML unit | val check_output_fields (ge: global_env) (flds: list out_field) : ML unit | let rec check_output_field (ge:global_env) (fld:out_field) : ML unit =
match fld with
| Out_field_named _ t _bopt -> check_integer_or_output_type (env_of_global_env ge) t
| Out_field_anon l _ -> check_output_fields ge l
and check_output_fields (ge:global_env) (flds:list out_field) : ML unit =
List.iter (check_output_field ge) flds | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 40,
"end_line": 1704,
"start_col": 0,
"start_line": 1698
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
]
let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None
let rec check_integer_or_output_type (env:env) (t:typ) : ML unit =
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] -> //either it should be a base type, or an output type
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else if not (k = KindOutput) then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
let check_mutable_param (env:env) (p:param) : ML unit =
//a mutable parameter should have a pointer type
//and the base type may be a base type or an output type
let t, _, _ = p in
match t.v with
| Pointer bt ->
check_mutable_param_type env bt
| _ ->
error (Printf.sprintf "%s is not a valid mutable parameter type, it is not a pointer type" (print_typ t)) t.range
let check_params (env:env) (ps:list param) : ML unit =
ps |> List.iter (fun (t, p, q) ->
if q = Mutable then check_mutable_param env (t, p, q)
else ignore (check_typ true env t);
add_local env p t)
let elaborate_record_decl (e:global_env)
(tdnames:Ast.typedef_names)
(params:list param)
(where:option expr)
(fields:list field)
(range:range)
(comments:comments)
(is_exported:bool)
: ML decl
= let env = { mk_env e with this=Some tdnames.typedef_name } in
(* Check parameters, that their types are well-formed;
extend the environments with them *)
check_params env params;
(* If a where-clause is present, elaborate it into a refined unit field *)
let where, maybe_unit_field =
match where with
| None ->
None, []
| Some e ->
let e, t = check_expr env e in
if not (eq_typ env t tbool)
then error (Printf.sprintf "Expected a boolean where clause; got %s"
(print_typ t))
e.range;
let w = Some e in
let field =
{ field_dependence = true;
field_ident = with_range (to_ident' "__precondition") e.range;
field_type = tunit;
field_array_opt = FieldScalar;
field_constraint = w;
field_bitwidth = None;
field_action = None;
field_probe = None
}
in
let af = with_range (AtomicField (with_range field e.range)) e.range in
w, [af]
in
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields = check_record check_field env fields in
let fields = maybe_unit_field@fields in
let fields = elaborate_bit_fields env fields in
let d = mk_decl (Record tdnames params where fields) range comments is_exported in
let attrs = {
may_fail = false; //only its fields may fail; not the struct itself
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = weak_kind_of_record env fields;
parser_kind_nz = None
}
in
add_global e tdnames.typedef_name d (Inl attrs);
d
(*
* An output field type is either a base type or another output type
*
* TODO: check field name shadowing
* TODO: check bit fields, do we check that the sum of bitwidths is ok etc.?
* as of now, we don't check anything here
*) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | ge: GlobalEnv.global_env -> flds: Prims.list Ast.out_field -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [
"check_output_field",
"check_output_fields"
] | [
"GlobalEnv.global_env",
"Prims.list",
"Ast.out_field",
"FStar.List.iter",
"Binding.check_output_field",
"Prims.unit"
] | [
"mutual recursion"
] | false | true | false | false | false | let rec check_output_fields (ge: global_env) (flds: list out_field) : ML unit =
| List.iter (check_output_field ge) flds | false |
Binding.fst | Binding.check_output_field | val check_output_field (ge: global_env) (fld: out_field) : ML unit | val check_output_field (ge: global_env) (fld: out_field) : ML unit | let rec check_output_field (ge:global_env) (fld:out_field) : ML unit =
match fld with
| Out_field_named _ t _bopt -> check_integer_or_output_type (env_of_global_env ge) t
| Out_field_anon l _ -> check_output_fields ge l
and check_output_fields (ge:global_env) (flds:list out_field) : ML unit =
List.iter (check_output_field ge) flds | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 40,
"end_line": 1704,
"start_col": 0,
"start_line": 1698
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
]
let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None
let rec check_integer_or_output_type (env:env) (t:typ) : ML unit =
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] -> //either it should be a base type, or an output type
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else if not (k = KindOutput) then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
let check_mutable_param (env:env) (p:param) : ML unit =
//a mutable parameter should have a pointer type
//and the base type may be a base type or an output type
let t, _, _ = p in
match t.v with
| Pointer bt ->
check_mutable_param_type env bt
| _ ->
error (Printf.sprintf "%s is not a valid mutable parameter type, it is not a pointer type" (print_typ t)) t.range
let check_params (env:env) (ps:list param) : ML unit =
ps |> List.iter (fun (t, p, q) ->
if q = Mutable then check_mutable_param env (t, p, q)
else ignore (check_typ true env t);
add_local env p t)
let elaborate_record_decl (e:global_env)
(tdnames:Ast.typedef_names)
(params:list param)
(where:option expr)
(fields:list field)
(range:range)
(comments:comments)
(is_exported:bool)
: ML decl
= let env = { mk_env e with this=Some tdnames.typedef_name } in
(* Check parameters, that their types are well-formed;
extend the environments with them *)
check_params env params;
(* If a where-clause is present, elaborate it into a refined unit field *)
let where, maybe_unit_field =
match where with
| None ->
None, []
| Some e ->
let e, t = check_expr env e in
if not (eq_typ env t tbool)
then error (Printf.sprintf "Expected a boolean where clause; got %s"
(print_typ t))
e.range;
let w = Some e in
let field =
{ field_dependence = true;
field_ident = with_range (to_ident' "__precondition") e.range;
field_type = tunit;
field_array_opt = FieldScalar;
field_constraint = w;
field_bitwidth = None;
field_action = None;
field_probe = None
}
in
let af = with_range (AtomicField (with_range field e.range)) e.range in
w, [af]
in
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields = check_record check_field env fields in
let fields = maybe_unit_field@fields in
let fields = elaborate_bit_fields env fields in
let d = mk_decl (Record tdnames params where fields) range comments is_exported in
let attrs = {
may_fail = false; //only its fields may fail; not the struct itself
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = weak_kind_of_record env fields;
parser_kind_nz = None
}
in
add_global e tdnames.typedef_name d (Inl attrs);
d
(*
* An output field type is either a base type or another output type
*
* TODO: check field name shadowing
* TODO: check bit fields, do we check that the sum of bitwidths is ok etc.?
* as of now, we don't check anything here
*) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | ge: GlobalEnv.global_env -> fld: Ast.out_field -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [
"check_output_field",
"check_output_fields"
] | [
"GlobalEnv.global_env",
"Ast.out_field",
"Ast.ident",
"Ast.typ",
"FStar.Pervasives.Native.option",
"Prims.int",
"Binding.check_integer_or_output_type",
"Binding.env_of_global_env",
"Prims.unit",
"Prims.list",
"Prims.bool",
"Binding.check_output_fields"
] | [
"mutual recursion"
] | false | true | false | false | false | let rec check_output_field (ge: global_env) (fld: out_field) : ML unit =
| match fld with
| Out_field_named _ t _bopt -> check_integer_or_output_type (env_of_global_env ge) t
| Out_field_anon l _ -> check_output_fields ge l | false |
Binding.fst | Binding.weak_kind_of_case | val weak_kind_of_case (env: env) (c: case) : ML weak_kind | val weak_kind_of_case (env: env) (c: case) : ML weak_kind | let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 40,
"end_line": 1262,
"start_col": 0,
"start_line": 1234
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> c: Ast.case -> FStar.All.ML Ast.weak_kind | FStar.All.ML | [
"ml"
] | [
"weak_kind_of_field",
"weak_kind_of_record",
"weak_kind_of_switch_case",
"weak_kind_of_case"
] | [
"Binding.env",
"Ast.case",
"Ast.with_meta_t",
"Ast.field'",
"Binding.weak_kind_of_field",
"Ast.weak_kind",
"Ast.expr"
] | [
"mutual recursion"
] | false | true | false | false | false | let rec weak_kind_of_case (env: env) (c: case) : ML weak_kind =
| match c with | DefaultCase f | Case _ f -> weak_kind_of_field env f | false |
Binding.fst | Binding.check_integer_or_output_type | val check_integer_or_output_type (env: env) (t: typ) : ML unit | val check_integer_or_output_type (env: env) (t: typ) : ML unit | let rec check_integer_or_output_type (env:env) (t:typ) : ML unit =
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] -> //either it should be a base type, or an output type
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else if not (k = KindOutput) then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 91,
"end_line": 1607,
"start_col": 0,
"start_line": 1599
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
]
let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> t: Ast.typ -> FStar.All.ML Prims.unit | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.typ",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.typ'",
"Ast.ident",
"Ast.t_kind",
"Prims.op_AmpAmp",
"Prims.op_Equality",
"FStar.Pervasives.Native.option",
"Prims.string",
"Ast.__proj__Mkident'__item__modul_name",
"Ast.ident'",
"FStar.Pervasives.Native.None",
"FStar.List.Tot.Base.mem",
"Ast.__proj__Mkident'__item__name",
"Binding.allowed_base_types_as_output_types",
"Prims.unit",
"Prims.bool",
"Prims.op_Negation",
"Ast.KindOutput",
"Ast.error",
"Ast.__proj__Mkwith_meta_t__item__range",
"FStar.Printf.sprintf",
"Ast.print_typ",
"Ast.with_meta_t",
"Binding.check_integer_or_output_type",
"Binding.unfold_typ_abbrev_only"
] | [
"recursion"
] | false | true | false | false | false | let rec check_integer_or_output_type (env: env) (t: typ) : ML unit =
| let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else
if not (k = KindOutput)
then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range | false |
Binding.fst | Binding.weak_kind_of_atomic_field | val weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind | val weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind | let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type)) | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 139,
"end_line": 1217,
"start_col": 0,
"start_line": 1212
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> f: Ast.atomic_field -> FStar.All.ML Ast.weak_kind | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.atomic_field",
"Binding.is_strong_prefix_field_array",
"Ast.__proj__Mkatomic_field'__item__field_array_opt",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.atomic_field'",
"Ast.WeakKindStrongPrefix",
"Ast.weak_kind",
"Prims.bool",
"FStar.All.failwith",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.print_ident",
"Ast.__proj__Mkatomic_field'__item__field_ident",
"Ast.print_typ",
"Ast.__proj__Mkatomic_field'__item__field_type",
"FStar.Pervasives.Native.option",
"Binding.typ_weak_kind"
] | [] | false | true | false | false | false | let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
| if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else
match typ_weak_kind env f.v.field_type with
| Some e -> e
| None ->
failwith (Printf.sprintf "cannot find the weak kind of field %s : %s"
(print_ident f.v.field_ident)
(print_typ f.v.field_type)) | false |
Binding.fst | Binding.finish_module | val finish_module (ge:global_env) (mname:string)
: ML global_env | val finish_module (ge:global_env) (mname:string)
: ML global_env | let finish_module ge mname =
let remove_private_decls (tbl:H.t ident' 'a) (f:'a -> decl) : ML unit =
let pvt_decls = H.fold (fun k v idents ->
if not (k.modul_name = Some mname)
then idents
else let d = f v in
if d.d_exported
then idents
else k::idents) tbl [] in
List.iter (H.remove tbl) pvt_decls in
remove_private_decls ge.ge_h (fun (d, _) -> d);
remove_private_decls ge.ge_out_t (fun d -> d);
remove_private_decls ge.ge_extern_t (fun d -> d);
remove_private_decls ge.ge_extern_fn (fun d -> d);
ge | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 4,
"end_line": 2044,
"start_col": 0,
"start_line": 2029
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
]
let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None
let rec check_integer_or_output_type (env:env) (t:typ) : ML unit =
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] -> //either it should be a base type, or an output type
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else if not (k = KindOutput) then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
let check_mutable_param (env:env) (p:param) : ML unit =
//a mutable parameter should have a pointer type
//and the base type may be a base type or an output type
let t, _, _ = p in
match t.v with
| Pointer bt ->
check_mutable_param_type env bt
| _ ->
error (Printf.sprintf "%s is not a valid mutable parameter type, it is not a pointer type" (print_typ t)) t.range
let check_params (env:env) (ps:list param) : ML unit =
ps |> List.iter (fun (t, p, q) ->
if q = Mutable then check_mutable_param env (t, p, q)
else ignore (check_typ true env t);
add_local env p t)
let elaborate_record_decl (e:global_env)
(tdnames:Ast.typedef_names)
(params:list param)
(where:option expr)
(fields:list field)
(range:range)
(comments:comments)
(is_exported:bool)
: ML decl
= let env = { mk_env e with this=Some tdnames.typedef_name } in
(* Check parameters, that their types are well-formed;
extend the environments with them *)
check_params env params;
(* If a where-clause is present, elaborate it into a refined unit field *)
let where, maybe_unit_field =
match where with
| None ->
None, []
| Some e ->
let e, t = check_expr env e in
if not (eq_typ env t tbool)
then error (Printf.sprintf "Expected a boolean where clause; got %s"
(print_typ t))
e.range;
let w = Some e in
let field =
{ field_dependence = true;
field_ident = with_range (to_ident' "__precondition") e.range;
field_type = tunit;
field_array_opt = FieldScalar;
field_constraint = w;
field_bitwidth = None;
field_action = None;
field_probe = None
}
in
let af = with_range (AtomicField (with_range field e.range)) e.range in
w, [af]
in
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields = check_record check_field env fields in
let fields = maybe_unit_field@fields in
let fields = elaborate_bit_fields env fields in
let d = mk_decl (Record tdnames params where fields) range comments is_exported in
let attrs = {
may_fail = false; //only its fields may fail; not the struct itself
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = weak_kind_of_record env fields;
parser_kind_nz = None
}
in
add_global e tdnames.typedef_name d (Inl attrs);
d
(*
* An output field type is either a base type or another output type
*
* TODO: check field name shadowing
* TODO: check bit fields, do we check that the sum of bitwidths is ok etc.?
* as of now, we don't check anything here
*)
let rec check_output_field (ge:global_env) (fld:out_field) : ML unit =
match fld with
| Out_field_named _ t _bopt -> check_integer_or_output_type (env_of_global_env ge) t
| Out_field_anon l _ -> check_output_fields ge l
and check_output_fields (ge:global_env) (flds:list out_field) : ML unit =
List.iter (check_output_field ge) flds
let bind_decl (e:global_env) (d:decl) : ML decl =
match d.d_decl.v with
| ModuleAbbrev i m -> d
| Define i None c ->
let t = type_of_constant d.d_decl.range c in
let d = decl_with_v d (Define i (Some t) c) in
add_global e i d (Inr (nullary_macro t (Some (with_range (Constant c) d.d_decl.range))));
d
| Define i (Some t) c ->
let env = mk_env e in
let t = check_typ false env t in
let t' = type_of_constant d.d_decl.range c in
let d = decl_with_v d (Define i (Some t) c) in
if eq_typ env t t'
then (add_global e i d (Inr (nullary_macro (type_of_constant d.d_decl.range c)
(Some (with_range (Constant c) d.d_decl.range))));
d)
else error "Ill-typed constant" d.d_decl.range
| TypeAbbrev t i ->
let env = mk_env e in
let t = check_typ false env t in
let wk =
match typ_weak_kind env t with
| None -> failwith (Printf.sprintf "Weak kind not found for type %s" (print_typ t))
| Some wk -> wk
in
let integral, bit_order = tag_and_bit_order_of_integral_typ env t in
let attrs =
{
may_fail = parser_may_fail env t;
integral = integral;
bit_order = bit_order;
has_reader = typ_has_reader env t;
parser_weak_kind = wk;
parser_kind_nz = None
}
in
let d = decl_with_v d (TypeAbbrev t i) in
add_global e i d (Inl attrs);
d
| Enum t i cases ->
let env = mk_env e in
let t = check_typ false env t in
let cases_idents = Desugar.check_desugared_enum_cases cases in
cases_idents |> List.iter (fun i ->
let _, t' = check_expr env (with_dummy_range (Identifier i)) in
if not (eq_typ env t t')
then error (Printf.sprintf "Inconsistent type of enumeration identifier: Expected %s, got %s"
(print_typ t)
(print_typ t'))
d.d_decl.range);
let integral = typ_as_integer_type t in
let bit_order = bit_order_of_typ t in
let attrs =
{
may_fail = true;
integral = Some integral;
bit_order = Some bit_order;
has_reader = false; //it's a refinement, so you can't read it again because of double fetches
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = None
}
in
let d = decl_with_v d (Enum t i cases) in
add_global e i d (Inl attrs);
d
| Record tdnames params where fields ->
elaborate_record_decl e tdnames params where fields d.d_decl.range d.d_decl.comments d.d_exported
| CaseType tdnames params switch ->
let env = { mk_env e with this=Some tdnames.typedef_name } in
check_params env params;
let switch = check_switch check_field env switch in
let wk = weak_kind_of_switch_case env switch in
let attrs = {
may_fail = false;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = wk;
parser_kind_nz = None
} in
let d = mk_decl (CaseType tdnames params switch) d.d_decl.range d.d_decl.comments d.d_exported in
add_global e tdnames.typedef_name d (Inl attrs);
d
| OutputType out_t ->
check_output_fields e out_t.out_typ_fields;
add_output_type e out_t.out_typ_names.typedef_name d;
d
| ExternType tdnames ->
add_extern_type e tdnames.typedef_name d;
d
| ExternFn f ret params ->
let env = mk_env e in
let ret = check_typ true env ret in
check_params env params;
let d = mk_decl (ExternFn f ret params) d.d_decl.range d.d_decl.comments d.d_exported in
add_extern_fn e f d;
d
| ExternProbe i ->
add_extern_probe e i d;
d
let bind_decls (g:global_env) (p:list decl) : ML (list decl & global_env) =
List.map (bind_decl g) p, g
let initial_global_env () =
let cfg = Deps.get_config () in
let e =
{
ge_h = H.create 10;
ge_out_t = H.create 10;
ge_extern_t = H.create 10;
ge_extern_fn = H.create 10;
ge_probe_fn = H.create 10;
ge_cfg = cfg
}
in
let nullary_decl i =
let td_name =
{ typedef_name = i; typedef_abbrev = i; typedef_ptr_abbrev = i; typedef_attributes = [] }
in
mk_decl (Record td_name [] None []) dummy_range [] true
in
let _type_names =
[
("unit",
{
may_fail = false;
integral = None;
bit_order = None;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some false
});
("Bool",
{
may_fail = true;
integral = None;
bit_order = None;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT8",
{
may_fail = true;
integral = Some UInt8;
bit_order = Some LSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT16",
{
may_fail = true;
integral = Some UInt16;
bit_order = Some LSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT32",
{
may_fail = true;
integral = Some UInt32;
bit_order = Some LSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT64",
{
may_fail = true;
integral = Some UInt64;
bit_order = Some LSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT8BE",
{
may_fail = true;
integral = Some UInt8;
bit_order = Some MSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT16BE",
{
may_fail = true;
integral = Some UInt16;
bit_order = Some MSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT32BE",
{
may_fail = true;
integral = Some UInt32;
bit_order = Some MSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("UINT64BE",
{
may_fail = true;
integral = Some UInt64;
bit_order = Some MSBFirst;
has_reader = true;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("field_id",
{
may_fail = true;
integral = Some UInt32;
bit_order = None;
has_reader = false;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("all_bytes",
{
may_fail = false;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = WeakKindConsumesAll;
parser_kind_nz = Some false
});
("all_zeros",
{
may_fail = true;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = WeakKindConsumesAll;
parser_kind_nz = Some false
});
("PUINT8",
{
may_fail = true;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
("EVERPARSE_COPY_BUFFER_T",
{
may_fail = true;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = Some true
});
] |>
List.iter (fun (i, attrs) ->
let i = with_dummy_range (to_ident' i) in
add_global e i (nullary_decl i) (Inl attrs))
in
let _operators =
[
("is_range_okay",
{
macro_arguments_t = [tuint32; tuint32; tuint32];
macro_result_t = tbool;
macro_defn_t = None
})
] |>
List.iter (fun (i, d) ->
let i = with_dummy_range (to_ident' i) in
add_global e i (nullary_decl i) (Inr d))
in
let _void =
let void_ident = with_dummy_range (to_ident' "void") in
add_extern_type e
void_ident
(mk_decl (ExternType
({
typedef_name = void_ident;
typedef_abbrev = void_ident;
typedef_ptr_abbrev = void_ident;
typedef_attributes = []
}))
dummy_range
[]
false)
in
let _ =
match cfg with
| None -> ()
| Some (cfg, module_name) ->
List.iter (fun flag ->
let ms = nullary_macro tbool None in
let i = with_dummy_range ({ to_ident' flag with modul_name = Some module_name }) in
let d = mk_decl (ExternFn i tbool []) dummy_range [] false in
add_global e i d (Inr ms))
cfg.compile_time_flags.flags
in
e
let get_exported_decls ge mname =
H.fold (fun k (d, _) (exported_decls, private_decls) ->
if not (k.modul_name = Some mname)
then exported_decls, private_decls
else if d.d_exported
then k::exported_decls, private_decls
else exported_decls, k::private_decls) ge.ge_h ([], []) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | ge: GlobalEnv.global_env -> mname: Prims.string -> FStar.All.ML GlobalEnv.global_env | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Prims.string",
"Prims.unit",
"Ast.decl",
"GlobalEnv.__proj__Mkglobal_env__item__ge_extern_fn",
"GlobalEnv.__proj__Mkglobal_env__item__ge_extern_t",
"GlobalEnv.__proj__Mkglobal_env__item__ge_out_t",
"FStar.Pervasives.Native.tuple2",
"Ast.either",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"GlobalEnv.__proj__Mkglobal_env__item__ge_h",
"Hashtable.t",
"Ast.ident'",
"FStar.List.iter",
"Hashtable.remove",
"Prims.list",
"Hashtable.fold",
"Prims.op_Negation",
"Prims.op_Equality",
"FStar.Pervasives.Native.option",
"Ast.__proj__Mkident'__item__modul_name",
"FStar.Pervasives.Native.Some",
"Prims.bool",
"Ast.__proj__Mkdecl__item__d_exported",
"Prims.Cons",
"Prims.Nil"
] | [] | false | true | false | false | false | let finish_module ge mname =
| let remove_private_decls (tbl: H.t ident' 'a) (f: ('a -> decl)) : ML unit =
let pvt_decls =
H.fold (fun k v idents ->
if not (k.modul_name = Some mname)
then idents
else
let d = f v in
if d.d_exported then idents else k :: idents)
tbl
[]
in
List.iter (H.remove tbl) pvt_decls
in
remove_private_decls ge.ge_h (fun (d, _) -> d);
remove_private_decls ge.ge_out_t (fun d -> d);
remove_private_decls ge.ge_extern_t (fun d -> d);
remove_private_decls ge.ge_extern_fn (fun d -> d);
ge | false |
Spec.Matrix.fst | Spec.Matrix.index_lt | val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2) | val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2) | let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
} | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 5,
"end_line": 33,
"start_col": 0,
"start_line": 24
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2) | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
n1: Lib.IntTypes.size_nat ->
n2: Lib.IntTypes.size_nat ->
i: Lib.IntTypes.size_nat{i < n1} ->
j: Lib.IntTypes.size_nat{j < n2}
-> FStar.Pervasives.Lemma (ensures i * n2 + j < n1 * n2) | FStar.Pervasives.Lemma | [
"lemma"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThan",
"FStar.Calc.calc_finish",
"Prims.int",
"Prims.op_LessThanOrEqual",
"Prims.op_Addition",
"FStar.Mul.op_Star",
"Prims.op_Subtraction",
"Prims.Cons",
"FStar.Preorder.relation",
"Prims.eq2",
"Prims.Nil",
"Prims.unit",
"FStar.Calc.calc_step",
"FStar.Calc.calc_init",
"FStar.Calc.calc_pack",
"FStar.Math.Lemmas.lemma_mult_le_right",
"Prims.squash",
"FStar.Math.Lemmas.distributivity_sub_left"
] | [] | false | false | true | false | false | let index_lt n1 n2 i j =
| calc ( <= ) {
i * n2 + j;
( <= ) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
( == ) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
( <= ) { () }
n1 * n2 - 1;
} | false |
Binding.fst | Binding.check_switch | val check_switch (check_field: check_field_t) (env: env) (s: switch_case) : ML switch_case | val check_switch (check_field: check_field_t) (env: env) (s: switch_case) : ML switch_case | let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases) | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 17,
"end_line": 1356,
"start_col": 0,
"start_line": 1269
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 8,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | check_field: Binding.check_field_t -> env: Binding.env -> s: Ast.switch_case
-> FStar.All.ML Ast.switch_case | FStar.All.ML | [
"ml"
] | [] | [
"Binding.check_field_t",
"Binding.env",
"Ast.switch_case",
"Ast.expr",
"Prims.list",
"Ast.case",
"Ast.typ",
"FStar.Pervasives.Native.Mktuple2",
"Prims.bool",
"FStar.List.fold_right",
"Ast.with_meta_t",
"Ast.field'",
"FStar.Exn.raise",
"Prims.exn",
"Ast.error",
"Ast.__proj__Mkwith_meta_t__item__range",
"FStar.List.map",
"Ast.uu___is_Case",
"Prims.b2t",
"Ast.uu___is_DefaultCase",
"Ast.DefaultCase",
"Ast.field",
"Ast.Case",
"FStar.Pervasives.Native.option",
"Ast.expr'",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.print_typ",
"Binding.try_cast_integer",
"Prims.op_Negation",
"Binding.eq_typ",
"Ast.ident",
"Ast.typ'",
"Prims.unit",
"Ast.print_expr",
"Ast.__proj__Mkwith_meta_t__item__v",
"FStar.Pervasives.Native.uu___is_Some",
"FStar.List.tryFind",
"Prims.op_Equality",
"Ast.ident'",
"FStar.Pervasives.Native.tuple2",
"Binding.check_expr",
"Ast.either",
"Ast.out_expr",
"FStar.Pervasives.Native.Some",
"Binding.try_lookup_enum_cases",
"Ast.t_kind",
"FStar.Pervasives.Native.None",
"Prims.op_AmpAmp",
"Ast.tbool",
"Binding.typ_is_integral"
] | [] | false | true | false | false | false | let check_switch (check_field: check_field_t) (env: env) (s: switch_case) : ML switch_case =
| let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a: Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral && not is_bool
then
error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c: case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat =
match tags_t_opt with
| None ->
if not (eq_typ env scrutinee_t pat_t)
then
match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
let case_exists =
match pat.v with
| Identifier pat -> Some? (List.tryFind (fun (case: ident) -> case.v = pat.v) enum_tags)
| _ -> false
in
if not (eq_typ env pat_t t)
then
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then
error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c: case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o: case) -> if Case? o then check_case o else check_default_case o) cases
in
let _ =
List.fold_right (fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok
then false
else raise (error "default is only allowed in the last case" f.range))
cases
true
in
(head, cases) | false |
Binding.fst | Binding.elaborate_record_decl | val elaborate_record_decl
(e: global_env)
(tdnames: Ast.typedef_names)
(params: list param)
(where: option expr)
(fields: list field)
(range: range)
(comments: comments)
(is_exported: bool)
: ML decl | val elaborate_record_decl
(e: global_env)
(tdnames: Ast.typedef_names)
(params: list param)
(where: option expr)
(fields: list field)
(range: range)
(comments: comments)
(is_exported: bool)
: ML decl | let elaborate_record_decl (e:global_env)
(tdnames:Ast.typedef_names)
(params:list param)
(where:option expr)
(fields:list field)
(range:range)
(comments:comments)
(is_exported:bool)
: ML decl
= let env = { mk_env e with this=Some tdnames.typedef_name } in
(* Check parameters, that their types are well-formed;
extend the environments with them *)
check_params env params;
(* If a where-clause is present, elaborate it into a refined unit field *)
let where, maybe_unit_field =
match where with
| None ->
None, []
| Some e ->
let e, t = check_expr env e in
if not (eq_typ env t tbool)
then error (Printf.sprintf "Expected a boolean where clause; got %s"
(print_typ t))
e.range;
let w = Some e in
let field =
{ field_dependence = true;
field_ident = with_range (to_ident' "__precondition") e.range;
field_type = tunit;
field_array_opt = FieldScalar;
field_constraint = w;
field_bitwidth = None;
field_action = None;
field_probe = None
}
in
let af = with_range (AtomicField (with_range field e.range)) e.range in
w, [af]
in
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields = check_record check_field env fields in
let fields = maybe_unit_field@fields in
let fields = elaborate_bit_fields env fields in
let d = mk_decl (Record tdnames params where fields) range comments is_exported in
let attrs = {
may_fail = false; //only its fields may fail; not the struct itself
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = weak_kind_of_record env fields;
parser_kind_nz = None
}
in
add_global e tdnames.typedef_name d (Inl attrs);
d | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 5,
"end_line": 1688,
"start_col": 0,
"start_line": 1626
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
]
let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None
let rec check_integer_or_output_type (env:env) (t:typ) : ML unit =
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] -> //either it should be a base type, or an output type
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else if not (k = KindOutput) then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
let check_mutable_param (env:env) (p:param) : ML unit =
//a mutable parameter should have a pointer type
//and the base type may be a base type or an output type
let t, _, _ = p in
match t.v with
| Pointer bt ->
check_mutable_param_type env bt
| _ ->
error (Printf.sprintf "%s is not a valid mutable parameter type, it is not a pointer type" (print_typ t)) t.range
let check_params (env:env) (ps:list param) : ML unit =
ps |> List.iter (fun (t, p, q) ->
if q = Mutable then check_mutable_param env (t, p, q)
else ignore (check_typ true env t);
add_local env p t) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
e: GlobalEnv.global_env ->
tdnames: Ast.typedef_names ->
params: Prims.list Ast.param ->
where: FStar.Pervasives.Native.option Ast.expr ->
fields: Prims.list Ast.field ->
range: Ast.range ->
comments: Ast.comments ->
is_exported: Prims.bool
-> FStar.All.ML Ast.decl | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.typedef_names",
"Prims.list",
"Ast.param",
"FStar.Pervasives.Native.option",
"Ast.expr",
"Ast.field",
"Ast.range",
"Ast.comments",
"Prims.bool",
"Ast.with_meta_t",
"Ast.field'",
"Ast.decl",
"Prims.unit",
"Binding.add_global",
"Ast.__proj__Mktypedef_names__item__typedef_name",
"Ast.Inl",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"GlobalEnv.Mkdecl_attributes",
"FStar.Pervasives.Native.None",
"Ast.integer_type",
"Ast.bitfield_bit_order",
"Ast.weak_kind",
"Binding.weak_kind_of_record",
"Ast.mk_decl",
"Ast.Record",
"Prims.eq2",
"Prims.nat",
"FStar.List.Tot.Base.length",
"Binding.elaborate_bit_fields",
"FStar.List.Tot.Base.op_At",
"Ast.record",
"Binding.check_record",
"Binding.check_field",
"FStar.Pervasives.Native.tuple2",
"FStar.Pervasives.Native.Mktuple2",
"Prims.Nil",
"Ast.typ",
"Prims.Cons",
"Ast.with_range",
"Ast.AtomicField",
"Ast.atomic_field'",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.expr'",
"Ast.Mkatomic_field'",
"Ast.ident'",
"Ast.to_ident'",
"Ast.tunit",
"Ast.FieldScalar",
"Ast.field_bitwidth_t",
"Ast.action",
"Ast.probe_call",
"FStar.Pervasives.Native.Some",
"Ast.error",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.print_typ",
"Prims.op_Negation",
"Binding.eq_typ",
"Ast.tbool",
"Binding.check_expr",
"Binding.check_params",
"Binding.env",
"Binding.Mkenv",
"Ast.ident",
"Binding.__proj__Mkenv__item__locals",
"Binding.__proj__Mkenv__item__globals",
"Binding.mk_env"
] | [] | false | true | false | false | false | let elaborate_record_decl
(e: global_env)
(tdnames: Ast.typedef_names)
(params: list param)
(where: option expr)
(fields: list field)
(range: range)
(comments: comments)
(is_exported: bool)
: ML decl =
| let env = { mk_env e with this = Some tdnames.typedef_name } in
check_params env params;
let where, maybe_unit_field =
match where with
| None -> None, []
| Some e ->
let e, t = check_expr env e in
if not (eq_typ env t tbool)
then error (Printf.sprintf "Expected a boolean where clause; got %s" (print_typ t)) e.range;
let w = Some e in
let field =
{
field_dependence = true;
field_ident = with_range (to_ident' "__precondition") e.range;
field_type = tunit;
field_array_opt = FieldScalar;
field_constraint = w;
field_bitwidth = None;
field_action = None;
field_probe = None
}
in
let af = with_range (AtomicField (with_range field e.range)) e.range in
w, [af]
in
let fields = check_record check_field env fields in
let fields = maybe_unit_field @ fields in
let fields = elaborate_bit_fields env fields in
let d = mk_decl (Record tdnames params where fields) range comments is_exported in
let attrs =
{
may_fail = false;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = weak_kind_of_record env fields;
parser_kind_nz = None
}
in
add_global e tdnames.typedef_name d (Inl attrs);
d | false |
Spec.Matrix.fst | Spec.Matrix.matrix | val matrix : n1: Lib.IntTypes.size_nat -> n2: Lib.IntTypes.size_nat{n1 * n2 <= Lib.IntTypes.max_size_t} -> Type0 | let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2) | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 88,
"end_line": 83,
"start_col": 0,
"start_line": 83
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16 | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | n1: Lib.IntTypes.size_nat -> n2: Lib.IntTypes.size_nat{n1 * n2 <= Lib.IntTypes.max_size_t} -> Type0 | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Lib.Sequence.lseq",
"Spec.Matrix.elem"
] | [] | false | false | false | false | true | let matrix (n1: size_nat) (n2: size_nat{n1 * n2 <= max_size_t}) =
| LSeq.lseq elem (n1 * n2) | false |
|
Spec.Matrix.fst | Spec.Matrix.mget | val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem | val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem | let mget #n1 #n2 a i j =
index_lt n1 n2 i j;
a.[i * n2 + j] | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 16,
"end_line": 99,
"start_col": 0,
"start_line": 97
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2)
val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2
let create n1 n2 = LSeq.create (n1 * n2) (u16 0)
val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | a: Spec.Matrix.matrix n1 n2 -> i: Lib.IntTypes.size_nat{i < n1} -> j: Lib.IntTypes.size_nat{j < n2}
-> Spec.Matrix.elem | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Spec.Matrix.matrix",
"Prims.op_LessThan",
"Lib.Sequence.op_String_Access",
"Spec.Matrix.elem",
"Prims.op_Addition",
"Prims.unit",
"Spec.Matrix.index_lt"
] | [] | false | false | false | false | false | let mget #n1 #n2 a i j =
| index_lt n1 n2 i j;
a.[ i * n2 + j ] | false |
Hacl.Bignum25519.fst | Hacl.Bignum25519.load_51 | val load_51:
output:lbuffer uint64 5ul
-> input:lbuffer uint8 32ul ->
Stack unit
(requires fun h -> live h output /\ live h input)
(ensures fun h0 _ h1 -> modifies (loc output) h0 h1 /\
F51.felem_fits h1 output (1, 1, 1, 1, 1) /\
F51.as_nat h1 output == (BSeq.nat_from_bytes_le (as_seq h0 input) % pow2 255)
) | val load_51:
output:lbuffer uint64 5ul
-> input:lbuffer uint8 32ul ->
Stack unit
(requires fun h -> live h output /\ live h input)
(ensures fun h0 _ h1 -> modifies (loc output) h0 h1 /\
F51.felem_fits h1 output (1, 1, 1, 1, 1) /\
F51.as_nat h1 output == (BSeq.nat_from_bytes_le (as_seq h0 input) % pow2 255)
) | let load_51 output input =
push_frame ();
let u64s = create 4ul (u64 0) in
let h0 = ST.get () in
uints_from_bytes_le #U64 u64s input;
let h1 = ST.get () in
BSeq.uints_from_bytes_le_nat_lemma #U64 #SEC #4 (as_seq h0 input);
assert (BSeq.nat_from_intseq_le (as_seq h1 u64s) == BSeq.nat_from_bytes_le (as_seq h0 input));
let u64s3 = u64s.(3ul) in
u64s.(3ul) <- u64s3 &. u64 0x7fffffffffffffff;
mod_mask_lemma u64s3 63ul;
assert_norm (0x7fffffffffffffff = pow2 63 - 1);
assert (v (mod_mask #U64 #SEC 63ul) == v (u64 0x7fffffffffffffff));
let h2 = ST.get () in
assert (v (LSeq.index (as_seq h2 u64s) 3) < pow2 63);
Hacl.Spec.Curve25519.Field64.Lemmas.lemma_felem64_mod255 (as_seq h1 u64s);
assert (BSeq.nat_from_intseq_le (as_seq h2 u64s) == BSeq.nat_from_bytes_le (as_seq h0 input) % pow2 255);
output.(0ul) <- u64s.(0ul) &. mask_51;
output.(1ul) <- (u64s.(0ul) >>. 51ul) |. ((u64s.(1ul) &. u64 0x3fffffffff) <<. 13ul);
output.(2ul) <- (u64s.(1ul) >>. 38ul) |. ((u64s.(2ul) &. u64 0x1ffffff) <<. 26ul);
output.(3ul) <- (u64s.(2ul) >>. 25ul) |. ((u64s.(3ul) &. u64 0xfff) <<. 39ul);
output.(4ul) <- u64s.(3ul) >>. 12ul;
SL51.lemma_load_felem (as_seq h2 u64s);
pop_frame () | {
"file_name": "code/ed25519/Hacl.Bignum25519.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 14,
"end_line": 276,
"start_col": 0,
"start_line": 251
} | module Hacl.Bignum25519
module ST = FStar.HyperStack.ST
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.ByteBuffer
module LSeq = Lib.Sequence
module BSeq = Lib.ByteSequence
module S51 = Hacl.Spec.Curve25519.Field51.Definition
module SL51 = Hacl.Spec.Curve25519.Field51.Lemmas
module BN = Hacl.Impl.Curve25519.Field51
module SC = Spec.Curve25519
friend Hacl.Curve25519_51
#reset-options "--z3rlimit 50 --max_fuel 0 --max_ifuel 0"
inline_for_extraction noextract
let mask_51 = u64 0x7ffffffffffff
let make_u64_5 b s0 s1 s2 s3 s4 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4
let make_u64_10 b s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 =
b.(0ul) <- s0;
b.(1ul) <- s1;
b.(2ul) <- s2;
b.(3ul) <- s3;
b.(4ul) <- s4;
b.(5ul) <- s5;
b.(6ul) <- s6;
b.(7ul) <- s7;
b.(8ul) <- s8;
b.(9ul) <- s9
let make_zero b =
b.(0ul) <- u64 0;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 0, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 0)
let make_one b =
b.(0ul) <- u64 1;
b.(1ul) <- u64 0;
b.(2ul) <- u64 0;
b.(3ul) <- u64 0;
b.(4ul) <- u64 0;
assert_norm (S51.as_nat5 (u64 1, u64 0, u64 0, u64 0, u64 0) % Spec.Curve25519.prime == 1)
[@CInline]
let fsum out a b =
BN.fadd out a b
[@CInline]
let fdifference out a b =
BN.fsub out a b
inline_for_extraction noextract
val carry51:
#m:S51.scale64{m < 8192}
-> l:uint64
-> cin:uint64 ->
Pure (uint64 & uint64)
(requires
S51.felem_fits1 l m /\
S51.felem_fits1 cin 1)
(ensures fun (l0, l1) ->
v l + v cin == v l1 * pow2 51 + v l0 /\
S51.felem_fits1 l0 1 /\ uint_v l1 < m + 1)
let carry51 l cin =
let l' = l +! cin in
mod_mask_lemma l' 51ul;
assert (v (mod_mask #U64 #SEC 51ul) == v mask_51);
FStar.Math.Lemmas.pow2_modulo_modulo_lemma_1 (v l') 51 64;
FStar.Math.Lemmas.euclidean_division_definition (v l') (pow2 51);
FStar.Math.Lemmas.pow2_minus 64 51;
(l' &. mask_51, l' >>. 51ul)
let reduce_513 a =
let (f0, f1, f2, f3, f4) = (a.(0ul), a.(1ul), a.(2ul), a.(3ul), a.(4ul)) in
let tmp0, c0 = carry51 #9 f0 (u64 0) in
let tmp1, c1 = carry51 #10 f1 c0 in
let tmp2, c2 = carry51 #9 f2 c1 in
let tmp3, c3 = carry51 #9 f3 c2 in
let tmp4, c4 = carry51 #9 f4 c3 in
assert (S51.felem_fits5 (tmp0, tmp1, tmp2, tmp3, tmp4) (1, 1, 1, 1, 1));
SL51.lemma_carry5_simplify c0 c1 c2 c3 c4 tmp0 tmp1 tmp2 tmp3 tmp4;
assert (
S51.as_nat5 (f0, f1, f2, f3, f4) % SC.prime ==
(S51.as_nat5 (tmp0, tmp1, tmp2, tmp3, tmp4) + v c4 * 19) % SC.prime);
[@inline_let]
let tmp0', c5 = carry51 #1 tmp0 (c4 *! u64 19) in
[@inline_let]
let tmp1' = tmp1 +! c5 in
Hacl.Spec.Curve25519.Field51.lemma_mul_inv (tmp0', tmp1, tmp2, tmp3, tmp4) c5;
make_u64_5 a tmp0' tmp1' tmp2 tmp3 tmp4
[@CInline]
let fmul output input input2 =
push_frame();
let tmp = create 10ul (u128 0) in
BN.fmul output input input2 tmp;
pop_frame()
[@CInline]
let times_2 out a =
(**) let h0 = ST.get() in
let a0 = a.(0ul) in
let a1 = a.(1ul) in
let a2 = a.(2ul) in
let a3 = a.(3ul) in
let a4 = a.(4ul) in
let o0 = u64 2 *. a0 in
let o1 = u64 2 *. a1 in
let o2 = u64 2 *. a2 in
let o3 = u64 2 *. a3 in
let o4 = u64 2 *. a4 in
make_u64_5 out o0 o1 o2 o3 o4;
(**) let h1 = ST.get() in
(**) assert (S51.felem_fits1 a0 1);
(**) assert (F51.felem_fits h1 out (2, 4, 2, 2, 2));
calc (==) {
(2 * (F51.fevalh h0 a)) % SC.prime;
(==) { calc (==) {
F51.fevalh h0 a;
(==) { }
S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime;
}
}
(2 * (S51.as_nat5 (a0, a1, a2, a3, a4) % SC.prime)) % SC.prime;
(==) { FStar.Math.Lemmas.lemma_mod_mul_distr_r 2 (S51.as_nat5 (a0, a1, a2, a3, a4)) SC.prime }
(2 * S51.as_nat5 (a0, a1, a2, a3, a4)) % SC.prime;
(==) { calc (==) {
2 * S51.as_nat5 (a0, a1, a2, a3, a4);
(==) { SL51.lemma_smul_felem5 (u64 2) (a0, a1, a2, a3, a4) }
2 * v a0 + 2 * v a1 * S51.pow51 + 2 * v a2 * S51.pow51 * S51.pow51 +
2 * v a3 * S51.pow51 * S51.pow51 * S51.pow51 +
2 * v a4 * S51.pow51 * S51.pow51 * S51.pow51 * S51.pow51;
(==) {
assert_norm (2 * S51.pow51 < pow2 64);
assert_norm (4 * S51.pow51 < pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a0) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a1) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a2) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a3) (pow2 64);
FStar.Math.Lemmas.small_mod (2 * v a4) (pow2 64)
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4);
}
}
S51.as_nat5 (u64 2 *. a0, u64 2 *. a1, u64 2 *. a2, u64 2 *. a3, u64 2 *. a4) % SC.prime;
(==) { }
F51.fevalh h1 out;
}
[@CInline]
let times_d out a =
push_frame();
let d = create 5ul (u64 0) in
d.(0ul) <- u64 0x00034dca135978a3;
d.(1ul) <- u64 0x0001a8283b156ebd;
d.(2ul) <- u64 0x0005e7a26001c029;
d.(3ul) <- u64 0x000739c663a03cbb;
d.(4ul) <- u64 0x00052036cee2b6ff;
assert_norm (S51.as_nat5 (u64 0x00034dca135978a3, u64 0x0001a8283b156ebd,
u64 0x0005e7a26001c029, u64 0x000739c663a03cbb, u64 0x00052036cee2b6ff) %
Spec.Curve25519.prime == Spec.Ed25519.d);
fmul out d a;
pop_frame()
[@CInline]
let times_2d out a =
push_frame();
let d2 = create 5ul (u64 0) in
d2.(0ul) <- u64 0x00069b9426b2f159;
d2.(1ul) <- u64 0x00035050762add7a;
d2.(2ul) <- u64 0x0003cf44c0038052;
d2.(3ul) <- u64 0x0006738cc7407977;
d2.(4ul) <- u64 0x0002406d9dc56dff;
fmul out d2 a;
assert_norm (S51.as_nat5 (u64 0x00069b9426b2f159, u64 0x00035050762add7a,
u64 0x0003cf44c0038052, u64 0x0006738cc7407977, u64 0x0002406d9dc56dff) %
Spec.Curve25519.prime == 2 `SC.fmul` Spec.Ed25519.d);
pop_frame()
[@CInline]
let fsquare out a =
push_frame();
let tmp = create 5ul (u128 0) in
BN.fsqr out a tmp;
pop_frame()
[@CInline]
let fsquare_times output input count =
push_frame();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output input tmp count;
pop_frame()
[@CInline]
let fsquare_times_inplace output count =
push_frame();
let tmp = create 5ul (u128 0) in
Hacl.Curve25519_51.fsquare_times output output tmp count;
pop_frame()
let inverse out a =
push_frame();
let tmp = create 10ul (u128 0) in
Hacl.Curve25519_51.finv out a tmp;
pop_frame()
[@CInline]
let reduce out =
let (o0, o1, o2, o3, o4) = (out.(0ul), out.(1ul), out.(2ul), out.(3ul), out.(4ul)) in
let (f0, f1, f2, f3, f4) = Hacl.Spec.Curve25519.Field51.carry_felem5_full (o0, o1, o2, o3, o4) in
let (f0, f1, f2, f3, f4) = Hacl.Spec.Curve25519.Field51.subtract_p5 (f0, f1, f2, f3, f4) in
Math.Lemmas.small_mod (S51.as_nat5 (f0, f1, f2, f3, f4)) Spec.Curve25519.prime;
make_u64_5 out f0 f1 f2 f3 f4 | {
"checked_file": "/",
"dependencies": [
"Spec.Ed25519.fst.checked",
"Spec.Curve25519.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"Lib.ByteBuffer.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.Spec.Curve25519.Field64.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Lemmas.fst.checked",
"Hacl.Spec.Curve25519.Field51.Definition.fst.checked",
"Hacl.Spec.Curve25519.Field51.fst.checked",
"Hacl.Impl.Curve25519.Field51.fst.checked",
"Hacl.Curve25519_51.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Hacl.Bignum25519.fst"
} | [
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Curve25519.Field51",
"short_module": "BN"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Lemmas",
"short_module": "SL51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": true,
"full_module": "Spec.Curve25519",
"short_module": "SC"
},
{
"abbrev": true,
"full_module": "Hacl.Impl.Ed25519.Field51",
"short_module": "F51"
},
{
"abbrev": true,
"full_module": "Hacl.Spec.Curve25519.Field51.Definition",
"short_module": "S51"
},
{
"abbrev": true,
"full_module": "Lib.ByteSequence",
"short_module": "BSeq"
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "ST"
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
output: Lib.Buffer.lbuffer Lib.IntTypes.uint64 5ul ->
input: Lib.Buffer.lbuffer Lib.IntTypes.uint8 32ul
-> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Lib.Buffer.lbuffer",
"Lib.IntTypes.uint64",
"FStar.UInt32.__uint_to_t",
"Lib.IntTypes.uint8",
"FStar.HyperStack.ST.pop_frame",
"Prims.unit",
"Hacl.Spec.Curve25519.Field51.Lemmas.lemma_load_felem",
"Lib.Buffer.as_seq",
"Lib.Buffer.MUT",
"Lib.IntTypes.uint_t",
"Lib.IntTypes.U64",
"Lib.IntTypes.SEC",
"Lib.Buffer.op_Array_Assignment",
"Lib.IntTypes.int_t",
"Lib.IntTypes.op_Greater_Greater_Dot",
"Lib.Buffer.op_Array_Access",
"Lib.IntTypes.op_Bar_Dot",
"Lib.IntTypes.op_Less_Less_Dot",
"Lib.IntTypes.op_Amp_Dot",
"Lib.IntTypes.u64",
"Hacl.Bignum25519.mask_51",
"Prims._assert",
"Prims.eq2",
"Prims.int",
"Lib.ByteSequence.nat_from_intseq_le",
"Prims.op_Modulus",
"Lib.ByteSequence.nat_from_bytes_le",
"Prims.pow2",
"Hacl.Spec.Curve25519.Field64.Lemmas.lemma_felem64_mod255",
"Prims.b2t",
"Prims.op_LessThan",
"Lib.IntTypes.v",
"Lib.Sequence.index",
"Lib.IntTypes.U32",
"Lib.IntTypes.PUB",
"FStar.Monotonic.HyperStack.mem",
"FStar.HyperStack.ST.get",
"Lib.IntTypes.range_t",
"Lib.IntTypes.mod_mask",
"FStar.Pervasives.assert_norm",
"Prims.op_Equality",
"Prims.op_Subtraction",
"Lib.IntTypes.mod_mask_lemma",
"Prims.nat",
"Prims.l_or",
"FStar.Mul.op_Star",
"Lib.Sequence.length",
"Lib.IntTypes.bits",
"Lib.IntTypes.U8",
"Lib.ByteSequence.uints_from_bytes_le_nat_lemma",
"Lib.ByteBuffer.uints_from_bytes_le",
"Lib.Buffer.lbuffer_t",
"FStar.UInt32.uint_to_t",
"FStar.UInt32.t",
"Lib.Buffer.create",
"FStar.HyperStack.ST.push_frame"
] | [] | false | true | false | false | false | let load_51 output input =
| push_frame ();
let u64s = create 4ul (u64 0) in
let h0 = ST.get () in
uints_from_bytes_le #U64 u64s input;
let h1 = ST.get () in
BSeq.uints_from_bytes_le_nat_lemma #U64 #SEC #4 (as_seq h0 input);
assert (BSeq.nat_from_intseq_le (as_seq h1 u64s) == BSeq.nat_from_bytes_le (as_seq h0 input));
let u64s3 = u64s.(3ul) in
u64s.(3ul) <- u64s3 &. u64 0x7fffffffffffffff;
mod_mask_lemma u64s3 63ul;
assert_norm (0x7fffffffffffffff = pow2 63 - 1);
assert (v (mod_mask #U64 #SEC 63ul) == v (u64 0x7fffffffffffffff));
let h2 = ST.get () in
assert (v (LSeq.index (as_seq h2 u64s) 3) < pow2 63);
Hacl.Spec.Curve25519.Field64.Lemmas.lemma_felem64_mod255 (as_seq h1 u64s);
assert (BSeq.nat_from_intseq_le (as_seq h2 u64s) ==
BSeq.nat_from_bytes_le (as_seq h0 input) % pow2 255);
output.(0ul) <- u64s.(0ul) &. mask_51;
output.(1ul) <- (u64s.(0ul) >>. 51ul) |. ((u64s.(1ul) &. u64 0x3fffffffff) <<. 13ul);
output.(2ul) <- (u64s.(1ul) >>. 38ul) |. ((u64s.(2ul) &. u64 0x1ffffff) <<. 26ul);
output.(3ul) <- (u64s.(2ul) >>. 25ul) |. ((u64s.(3ul) &. u64 0xfff) <<. 39ul);
output.(4ul) <- u64s.(3ul) >>. 12ul;
SL51.lemma_load_felem (as_seq h2 u64s);
pop_frame () | false |
Binding.fst | Binding.check_field_action | val check_field_action (env: env) (f: atomic_field) (a: action) : ML (action & typ) | val check_field_action (env: env) (f: atomic_field) (a: action) : ML (action & typ) | let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 24,
"end_line": 1092,
"start_col": 0,
"start_line": 959
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3" | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 3,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> f: Ast.atomic_field -> a: Ast.action -> FStar.All.ML (Ast.action * Ast.typ) | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Ast.atomic_field",
"Ast.action",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.action'",
"Ast.atomic_action",
"Ast.typ",
"FStar.Pervasives.Native.Mktuple2",
"Ast.Mkwith_meta_t",
"Ast.Atomic_action",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.__proj__Mkwith_meta_t__item__comments",
"FStar.Pervasives.Native.tuple2",
"Ast.with_meta_t",
"Ast.Action_seq",
"Binding.check_field_action",
"Ast.expr",
"FStar.Pervasives.Native.option",
"Ast.typ'",
"Ast.Action_ite",
"Prims.unit",
"Prims.op_BarBar",
"Prims.op_Negation",
"Prims.op_AmpAmp",
"FStar.Pervasives.Native.uu___is_None",
"Ast.error",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.print_typ",
"Prims.bool",
"Binding.eq_typ",
"Ast.tunit",
"FStar.Pervasives.Native.None",
"FStar.Pervasives.Native.Some",
"Ast.expr'",
"Ast.print_expr",
"Ast.tbool",
"Binding.check_expr",
"Ast.ident",
"Ast.Action_let",
"Binding.remove_local",
"Binding.add_local",
"Ast.Action_act",
"Ast.range",
"Ast.Action_return",
"Ast.Action_abort",
"Ast.Action_field_pos_64",
"Ast.tuint64",
"Ast.Action_field_pos_32",
"Ast.tuint32",
"Ast.Action_field_ptr",
"Ast.puint8",
"Ast.out_expr",
"Prims.int",
"Ast.out_expr'",
"Ast.__proj__Mkout_expr__item__out_expr_node",
"Ast.print_out_expr",
"Ast.Action_field_ptr_after",
"Ast.out_expr_meta_t",
"FStar.Pervasives.Native.__proj__Some__item__v",
"Ast.__proj__Mkout_expr__item__out_expr_meta",
"Prims.b2t",
"FStar.Pervasives.Native.uu___is_Some",
"Binding.check_out_expr",
"Ast.Action_deref",
"Ast.ident'",
"Binding.lookup_expr_name",
"Ast.Action_assignment",
"Ast.warning",
"Binding.try_cast_integer",
"Prims.list",
"Ast.param",
"Prims.op_disEquality",
"Prims.nat",
"FStar.List.Tot.Base.length",
"Ast.ident_to_string",
"Ast.Action_call",
"FStar.List.map2",
"FStar.Pervasives.Native.tuple3",
"Ast.qualifier",
"Binding.lookup_extern_fn",
"GlobalEnv.global_env",
"Binding.global_env_of_env"
] | [
"recursion"
] | false | true | false | false | false | let rec check_field_action (env: env) (f: atomic_field) (a: action) : ML (action & typ) =
| let check_atomic_action env (r: range) (a: atomic_action) : ML (atomic_action & typ) =
match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort -> Action_abort, tunit
| Action_field_pos_64 -> Action_field_pos_64, tuint64
| Action_field_pos_32 -> Action_field_pos_32, tuint32
| Action_field_ptr -> Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t))
e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et))
write_to.out_expr_node.range
else Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
(match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range)
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then
match try_cast_integer env (rhs, t') t with
| Some rhs -> Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf "Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then
error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f))
f.range
else
let args =
List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg))
arg.range
else arg)
params
args
in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v = Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v = Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then
error (Printf.sprintf "Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t || (None? else_ && not eq_t_unit)
then
error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit" (print_typ t)) a.range | false |
Binding.fst | Binding.bind_decl | val bind_decl (e: global_env) (d: decl) : ML decl | val bind_decl (e: global_env) (d: decl) : ML decl | let bind_decl (e:global_env) (d:decl) : ML decl =
match d.d_decl.v with
| ModuleAbbrev i m -> d
| Define i None c ->
let t = type_of_constant d.d_decl.range c in
let d = decl_with_v d (Define i (Some t) c) in
add_global e i d (Inr (nullary_macro t (Some (with_range (Constant c) d.d_decl.range))));
d
| Define i (Some t) c ->
let env = mk_env e in
let t = check_typ false env t in
let t' = type_of_constant d.d_decl.range c in
let d = decl_with_v d (Define i (Some t) c) in
if eq_typ env t t'
then (add_global e i d (Inr (nullary_macro (type_of_constant d.d_decl.range c)
(Some (with_range (Constant c) d.d_decl.range))));
d)
else error "Ill-typed constant" d.d_decl.range
| TypeAbbrev t i ->
let env = mk_env e in
let t = check_typ false env t in
let wk =
match typ_weak_kind env t with
| None -> failwith (Printf.sprintf "Weak kind not found for type %s" (print_typ t))
| Some wk -> wk
in
let integral, bit_order = tag_and_bit_order_of_integral_typ env t in
let attrs =
{
may_fail = parser_may_fail env t;
integral = integral;
bit_order = bit_order;
has_reader = typ_has_reader env t;
parser_weak_kind = wk;
parser_kind_nz = None
}
in
let d = decl_with_v d (TypeAbbrev t i) in
add_global e i d (Inl attrs);
d
| Enum t i cases ->
let env = mk_env e in
let t = check_typ false env t in
let cases_idents = Desugar.check_desugared_enum_cases cases in
cases_idents |> List.iter (fun i ->
let _, t' = check_expr env (with_dummy_range (Identifier i)) in
if not (eq_typ env t t')
then error (Printf.sprintf "Inconsistent type of enumeration identifier: Expected %s, got %s"
(print_typ t)
(print_typ t'))
d.d_decl.range);
let integral = typ_as_integer_type t in
let bit_order = bit_order_of_typ t in
let attrs =
{
may_fail = true;
integral = Some integral;
bit_order = Some bit_order;
has_reader = false; //it's a refinement, so you can't read it again because of double fetches
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = None
}
in
let d = decl_with_v d (Enum t i cases) in
add_global e i d (Inl attrs);
d
| Record tdnames params where fields ->
elaborate_record_decl e tdnames params where fields d.d_decl.range d.d_decl.comments d.d_exported
| CaseType tdnames params switch ->
let env = { mk_env e with this=Some tdnames.typedef_name } in
check_params env params;
let switch = check_switch check_field env switch in
let wk = weak_kind_of_switch_case env switch in
let attrs = {
may_fail = false;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = wk;
parser_kind_nz = None
} in
let d = mk_decl (CaseType tdnames params switch) d.d_decl.range d.d_decl.comments d.d_exported in
add_global e tdnames.typedef_name d (Inl attrs);
d
| OutputType out_t ->
check_output_fields e out_t.out_typ_fields;
add_output_type e out_t.out_typ_names.typedef_name d;
d
| ExternType tdnames ->
add_extern_type e tdnames.typedef_name d;
d
| ExternFn f ret params ->
let env = mk_env e in
let ret = check_typ true env ret in
check_params env params;
let d = mk_decl (ExternFn f ret params) d.d_decl.range d.d_decl.comments d.d_exported in
add_extern_fn e f d;
d
| ExternProbe i ->
add_extern_probe e i d;
d | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 5,
"end_line": 1815,
"start_col": 0,
"start_line": 1706
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options
#push-options "--z3rlimit_factor 4"
let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf }
let is_strong_prefix_field_array (a: field_array_t) : Tot bool =
not (FieldScalar? a)
let weak_kind_of_atomic_field (env: env) (f: atomic_field) : ML weak_kind =
if is_strong_prefix_field_array f.v.field_array_opt
then WeakKindStrongPrefix
else match typ_weak_kind env f.v.field_type with
| Some e -> e
| None -> failwith (Printf.sprintf "cannot find the weak kind of field %s : %s" (print_ident f.v.field_ident) (print_typ f.v.field_type))
let weak_kind_of_list (wa:'a -> ML weak_kind) (xs:list 'a) : ML weak_kind =
let k =
List.fold_left
(fun out f ->
let fk = wa f in
match out with
| None -> Some fk
| Some o -> Some (weak_kind_glb o fk))
None
xs
in
match k with
| None -> WeakKindWeak
| Some k -> k
let rec weak_kind_of_field (env: env) (f: field) : ML weak_kind =
match f.v with
| AtomicField f -> weak_kind_of_atomic_field env f
| RecordField f _ -> weak_kind_of_record env f
| SwitchCaseField f _ -> weak_kind_of_switch_case env f
and weak_kind_of_record env (fs:record) : ML weak_kind =
match fs with
| [] -> WeakKindStrongPrefix
| [a] -> weak_kind_of_field env a
| a :: q ->
let wk = weak_kind_of_field env a in
if wk <> WeakKindStrongPrefix
then failwith
(Printf.sprintf "weak_kind_of_fields: \
field %s should be of strong kind \
instead of %s"
(print_field a)
(print_weak_kind wk))
else weak_kind_of_record env q
and weak_kind_of_switch_case env (s:switch_case) : ML weak_kind =
let _, cases = s in
weak_kind_of_list (weak_kind_of_case env) cases
and weak_kind_of_case (env: env) (c: case) : ML weak_kind =
match c with
| DefaultCase f
| Case _ f -> weak_kind_of_field env f
#pop-options
let check_field_t = env -> field -> ML field
#push-options "--z3rlimit_factor 8"
let check_switch (check_field:check_field_t) (env:env) (s:switch_case)
: ML switch_case
= let head, cases = s in
let head, scrutinee_t = check_expr env head in
let fail_non_equality_type (#a:Type) () : ML (option a) =
let integral = typ_is_integral env scrutinee_t in
let is_bool = eq_typ env scrutinee_t tbool in
if not integral
&& not is_bool
then error (Printf.sprintf "Case analysis of a non-integral or non-boolean type (%s) is not supported"
(print_typ scrutinee_t))
head.range;
None
in
let tags_t_opt =
match scrutinee_t.v with
| Pointer _ -> fail_non_equality_type ()
| Type_app hd KindSpec es ->
(match try_lookup_enum_cases env hd with
| Some enum -> Some enum
| _ -> fail_non_equality_type ())
| Type_app _ _ _ ->
error "Impossible, check_switch is not supposed to typecheck output/extern types!" head.range
in
let check_case (c:case{Case? c}) : ML case =
let Case pat f = c in
let pat, pat_t = check_expr env pat in
let f = check_field env f in
let pat = //check type of patterns
match tags_t_opt with
| None ->
//Not an enum; just check that its a valid u32
if not (eq_typ env scrutinee_t pat_t)
then match try_cast_integer env (pat, pat_t) scrutinee_t with
| Some pat -> pat
| _ ->
error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ scrutinee_t))
pat.range
else pat
| Some (enum_tags, t) ->
//expected an enumerated type;
//check that patterns are valid cases of the enum
let case_exists =
match pat.v with
| Identifier pat ->
Some? (List.tryFind (fun (case:ident) -> case.v = pat.v) enum_tags)
| _ ->
false
in
if not (eq_typ env pat_t t)
then error (Printf.sprintf "Type of case (%s) does not match type of switch expression (%s)"
(print_typ pat_t)
(print_typ t))
pat.range;
if not case_exists
then error (Printf.sprintf "Case (%s) is not in the enumerated type %s"
(print_expr pat)
(print_typ scrutinee_t))
pat.range;
pat
in
Case pat f
in
let check_default_case (c:case{DefaultCase? c}) : ML case =
let DefaultCase f = c in
let f = check_field env f in
DefaultCase f
in
let cases =
List.map (fun (o:case) -> if Case? o then check_case o else check_default_case o) cases in
let _ =
List.fold_right
(fun case default_ok ->
match case with
| Case _ _ -> false
| DefaultCase f ->
if default_ok then false
else raise (error "default is only allowed in the last case"
f.range))
cases
true
in
(head, cases)
#pop-options
let is_bound_locally (env:env) (i:ident) =
match H.try_find env.locals i.v with
| None -> false
| Some _ -> true
let rec check_record (check_field:check_field_t) (env:env) (fs:record)
: ML record
= let env = copy_env env in //locals of a record do not escape the record
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields =
List.map
(fun f ->
match f.v with
| AtomicField af ->
let af = check_atomic_field env true af in
{ f with v = AtomicField af }
| RecordField fs i ->
let fs = check_record check_field env fs in
{f with v = RecordField fs i }
| SwitchCaseField swc i ->
let swc = check_switch check_field env swc in
{ f with v = SwitchCaseField swc i})
fs
in
(* Infer which of the fields are dependent by seeing which of them are used in refinements *)
let nfields = List.length fields in
let fields = fields |> List.mapi (fun i f ->
match f.v with
| RecordField _ _
| SwitchCaseField _ _ -> f
| AtomicField af ->
let sf = af.v in
let used = is_used env sf.field_ident in
let last_field = i = (nfields - 1) in
let dependent = used || (Some? sf.field_constraint && not last_field) in
let af =
with_range_and_comments
({ sf with field_dependence = dependent })
af.range
af.comments
in
let has_reader = typ_has_reader env af.v.field_type in
let is_enum = is_enum env af.v.field_type in
if af.v.field_dependence
&& not has_reader
&& not is_enum //if it's an enum, it can be inlined later to allow dependence
then error "The type of this field does not have a reader, \
either because its values are too large \
or because reading it may incur a double fetch; \
subsequent fields cannot depend on it" af.range
else { f with v = AtomicField af })
in
fields
let name_of_field (f:field) : ident =
match f.v with
| AtomicField af -> af.v.field_ident
| RecordField _ i
| SwitchCaseField _ i -> i
let check_field_names_unique (f:list field)
: ML unit
= match f with
| []
| [_] -> ()
| hd::tl ->
let i = name_of_field hd in
if List.for_all (fun f' -> not (eq_idents (name_of_field f') i)) tl
then ()
else error (Printf.sprintf "Field name %s is not unique" i.v.name) i.range
let rec check_field (env:env) (f:field)
: ML field
= match f.v with
| AtomicField af ->
{ f with v = AtomicField (check_atomic_field env false af) }
| RecordField fs i ->
check_field_names_unique fs;
{ f with v = RecordField (check_record check_field env fs) i }
| SwitchCaseField swc i ->
{ f with v = SwitchCaseField (check_switch check_field env swc) i }
(** Computes a layout for bit fields,
decorating each field with a bitfield index
and a bit range within that bitfield to store the given field.
Collapsing adjacent bitfields into a single field is done in a
separate phase, see BitFields.fst
*)
let elaborate_bit_fields env (fields:list field)
: ML (out:list field { List.length out == List.length fields })
= let bf_index : ref int = ST.alloc 0 in
let get_bf_index () = !bf_index in
let next_bf_index () = bf_index := !bf_index + 1 in
let new_bit_field (sf:atomic_field') bw r : ML (atomic_field & option (typ & int & int)) =
let index = get_bf_index () in
let size = size_of_integral_typ env sf.field_type r in
let bit_size = 8 * size in
let remaining_size = bit_size - bw.v in
let from = 0 in
let to = bw.v in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = sf.field_type;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr r)) } in
with_range sf r,
Some (sf.field_type, to, remaining_size)
in
let rec aux open_bit_field fields
: ML (out:list field { List.length out == List.length fields } )
= match fields with
| [] ->
[]
| hd::tl ->
begin
match hd.v with
| RecordField fs hd_fieldname ->
next_bf_index();
let fs = aux None fs in
let hd = { hd with v = RecordField fs hd_fieldname } in
next_bf_index();
hd :: aux None tl
| SwitchCaseField (e, cases) hd_fieldname ->
next_bf_index();
let cases =
List.map
(function
| Case p f ->
let [f] = aux None [f] in
Case p f
| DefaultCase f ->
let [f] = aux None [f] in
DefaultCase f)
cases
in
next_bf_index();
let hd = { hd with v = SwitchCaseField (e, cases) hd_fieldname } in
hd :: aux None tl
| AtomicField af ->
let sf = af.v in
match sf.field_bitwidth, open_bit_field with
| None, None ->
hd :: aux open_bit_field tl
| None, Some _ -> //end the bit field
next_bf_index();
hd :: aux None tl
| Some (Inr _), _ ->
failwith "Bitfield is already elaborated"
| Some (Inl bw), None ->
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
| Some (Inl bw), Some (bit_field_typ, pos, remaining_size) ->
Options.debug_print_string
(Printf.sprintf
"Field type = %s; bit_field_type = %s\n"
(print_typ sf.field_type)
(print_typ bit_field_typ));
let type_matches_current_open_field = eq_typ env sf.field_type bit_field_typ in
if remaining_size < bw.v //not enough space in this bit field, start a new one
|| not type_matches_current_open_field
then let _ = next_bf_index () in
let af, open_bit_field = new_bit_field sf bw hd.range in
let tl = aux open_bit_field tl in
{ hd with v = AtomicField af } :: tl
else //extend this bit field
begin
let remaining_size = remaining_size - bw.v in
let from = pos in
let to = pos + bw.v in
let index = get_bf_index() in
let bf_attr = {
bitfield_width = bw.v;
bitfield_identifier = index;
bitfield_type = bit_field_typ;
bitfield_from = from;
bitfield_to = to
} in
let sf = { sf with field_bitwidth = Some (Inr (with_range bf_attr bw.range)) } in
let af = { af with v = sf } in
let hd = { hd with v = AtomicField af } in
let open_bit_field = Some (bit_field_typ, to, remaining_size) in
let tl = aux open_bit_field tl in
hd :: tl
end
end
in
aux None fields
let allowed_base_types_as_output_types = [
"UINT8"; "UINT16"; "UINT32"; "UINT64";
"UINT8BE"; "UINT16BE"; "UINT32BE"; "UINT64BE";
"PUINT8";
"Bool"
]
let rec check_mutable_param_type (env:env) (t:typ) : ML unit =
let err iopt : ML unit =
let otype =
match iopt with
| None -> "None"
| Some i ->
match H.try_find env.globals.ge_out_t i.v with
| Some d ->
Printf.sprintf "(Some %s)" (print_decl d)
| _ -> "None"
in
error (Printf.sprintf "%s is not an integer or output or extern type (found decl %s)" (print_typ t) otype) t.range in
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] ->
if k = KindOutput || k = KindExtern ||
(i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types)
then ()
else err (Some i)
| Pointer t -> check_mutable_param_type env t
| _ -> err None
let rec check_integer_or_output_type (env:env) (t:typ) : ML unit =
let t = unfold_typ_abbrev_only env t in
match t.v with
| Type_app i k [] -> //either it should be a base type, or an output type
if i.v.modul_name = None && List.Tot.mem i.v.name allowed_base_types_as_output_types
then ()
else if not (k = KindOutput) then error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
| Pointer t -> check_integer_or_output_type env t
| _ -> error (Printf.sprintf "%s is not an integer or output type" (print_typ t)) t.range
let check_mutable_param (env:env) (p:param) : ML unit =
//a mutable parameter should have a pointer type
//and the base type may be a base type or an output type
let t, _, _ = p in
match t.v with
| Pointer bt ->
check_mutable_param_type env bt
| _ ->
error (Printf.sprintf "%s is not a valid mutable parameter type, it is not a pointer type" (print_typ t)) t.range
let check_params (env:env) (ps:list param) : ML unit =
ps |> List.iter (fun (t, p, q) ->
if q = Mutable then check_mutable_param env (t, p, q)
else ignore (check_typ true env t);
add_local env p t)
let elaborate_record_decl (e:global_env)
(tdnames:Ast.typedef_names)
(params:list param)
(where:option expr)
(fields:list field)
(range:range)
(comments:comments)
(is_exported:bool)
: ML decl
= let env = { mk_env e with this=Some tdnames.typedef_name } in
(* Check parameters, that their types are well-formed;
extend the environments with them *)
check_params env params;
(* If a where-clause is present, elaborate it into a refined unit field *)
let where, maybe_unit_field =
match where with
| None ->
None, []
| Some e ->
let e, t = check_expr env e in
if not (eq_typ env t tbool)
then error (Printf.sprintf "Expected a boolean where clause; got %s"
(print_typ t))
e.range;
let w = Some e in
let field =
{ field_dependence = true;
field_ident = with_range (to_ident' "__precondition") e.range;
field_type = tunit;
field_array_opt = FieldScalar;
field_constraint = w;
field_bitwidth = None;
field_action = None;
field_probe = None
}
in
let af = with_range (AtomicField (with_range field e.range)) e.range in
w, [af]
in
(* Elaborate and check each field in order;
Checking each field extends the local environment with the name of that field *)
let fields = check_record check_field env fields in
let fields = maybe_unit_field@fields in
let fields = elaborate_bit_fields env fields in
let d = mk_decl (Record tdnames params where fields) range comments is_exported in
let attrs = {
may_fail = false; //only its fields may fail; not the struct itself
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = weak_kind_of_record env fields;
parser_kind_nz = None
}
in
add_global e tdnames.typedef_name d (Inl attrs);
d
(*
* An output field type is either a base type or another output type
*
* TODO: check field name shadowing
* TODO: check bit fields, do we check that the sum of bitwidths is ok etc.?
* as of now, we don't check anything here
*)
let rec check_output_field (ge:global_env) (fld:out_field) : ML unit =
match fld with
| Out_field_named _ t _bopt -> check_integer_or_output_type (env_of_global_env ge) t
| Out_field_anon l _ -> check_output_fields ge l
and check_output_fields (ge:global_env) (flds:list out_field) : ML unit =
List.iter (check_output_field ge) flds | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | e: GlobalEnv.global_env -> d: Ast.decl -> FStar.All.ML Ast.decl | FStar.All.ML | [
"ml"
] | [] | [
"GlobalEnv.global_env",
"Ast.decl",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.decl'",
"Ast.__proj__Mkdecl__item__d_decl",
"Ast.ident",
"Ast.constant",
"Prims.unit",
"Binding.add_global",
"Ast.Inr",
"GlobalEnv.decl_attributes",
"GlobalEnv.macro_signature",
"GlobalEnv.nullary_macro",
"FStar.Pervasives.Native.Some",
"Ast.expr",
"Ast.with_range",
"Ast.expr'",
"Ast.Constant",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.decl_with_v",
"Ast.Define",
"Ast.typ",
"Binding.type_of_constant",
"Ast.either",
"Prims.bool",
"Ast.error",
"Binding.eq_typ",
"Binding.check_typ",
"Binding.env",
"Binding.mk_env",
"FStar.Pervasives.Native.option",
"Ast.integer_type",
"Ast.bitfield_bit_order",
"Ast.Inl",
"Ast.TypeAbbrev",
"GlobalEnv.Mkdecl_attributes",
"FStar.Pervasives.Native.None",
"Binding.typ_has_reader",
"Binding.parser_may_fail",
"FStar.Pervasives.Native.tuple2",
"Prims.l_imp",
"Prims.b2t",
"FStar.Pervasives.Native.uu___is_Some",
"FStar.Pervasives.Native.snd",
"FStar.Pervasives.Native.fst",
"Binding.tag_and_bit_order_of_integral_typ",
"Ast.weak_kind",
"FStar.All.failwith",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.print_typ",
"Binding.typ_weak_kind",
"Prims.list",
"Ast.enum_case",
"Ast.Enum",
"Ast.WeakKindStrongPrefix",
"Ast.bit_order_of_typ",
"Ast.typ_as_integer_type",
"FStar.List.iter",
"Prims.op_Negation",
"Binding.check_expr",
"Ast.with_dummy_range",
"Ast.Identifier",
"Desugar.check_desugared_enum_cases",
"Ast.typedef_names",
"Ast.param",
"Ast.record",
"Binding.elaborate_record_decl",
"Ast.__proj__Mkwith_meta_t__item__comments",
"Ast.__proj__Mkdecl__item__d_exported",
"Ast.switch_case",
"Ast.__proj__Mktypedef_names__item__typedef_name",
"Ast.mk_decl",
"Ast.CaseType",
"Binding.weak_kind_of_switch_case",
"Binding.check_switch",
"Binding.check_field",
"Binding.check_params",
"Binding.Mkenv",
"Binding.__proj__Mkenv__item__locals",
"Binding.__proj__Mkenv__item__globals",
"Ast.out_typ",
"Binding.add_output_type",
"Ast.__proj__Mkout_typ__item__out_typ_names",
"Binding.check_output_fields",
"Ast.__proj__Mkout_typ__item__out_typ_fields",
"Binding.add_extern_type",
"Binding.add_extern_fn",
"Ast.ExternFn",
"Binding.add_extern_probe"
] | [] | false | true | false | false | false | let bind_decl (e: global_env) (d: decl) : ML decl =
| match d.d_decl.v with
| ModuleAbbrev i m -> d
| Define i None c ->
let t = type_of_constant d.d_decl.range c in
let d = decl_with_v d (Define i (Some t) c) in
add_global e i d (Inr (nullary_macro t (Some (with_range (Constant c) d.d_decl.range))));
d
| Define i (Some t) c ->
let env = mk_env e in
let t = check_typ false env t in
let t' = type_of_constant d.d_decl.range c in
let d = decl_with_v d (Define i (Some t) c) in
if eq_typ env t t'
then
(add_global e
i
d
(Inr
(nullary_macro (type_of_constant d.d_decl.range c)
(Some (with_range (Constant c) d.d_decl.range))));
d)
else error "Ill-typed constant" d.d_decl.range
| TypeAbbrev t i ->
let env = mk_env e in
let t = check_typ false env t in
let wk =
match typ_weak_kind env t with
| None -> failwith (Printf.sprintf "Weak kind not found for type %s" (print_typ t))
| Some wk -> wk
in
let integral, bit_order = tag_and_bit_order_of_integral_typ env t in
let attrs =
{
may_fail = parser_may_fail env t;
integral = integral;
bit_order = bit_order;
has_reader = typ_has_reader env t;
parser_weak_kind = wk;
parser_kind_nz = None
}
in
let d = decl_with_v d (TypeAbbrev t i) in
add_global e i d (Inl attrs);
d
| Enum t i cases ->
let env = mk_env e in
let t = check_typ false env t in
let cases_idents = Desugar.check_desugared_enum_cases cases in
cases_idents |>
List.iter (fun i ->
let _, t' = check_expr env (with_dummy_range (Identifier i)) in
if not (eq_typ env t t')
then
error (Printf.sprintf "Inconsistent type of enumeration identifier: Expected %s, got %s"
(print_typ t)
(print_typ t'))
d.d_decl.range);
let integral = typ_as_integer_type t in
let bit_order = bit_order_of_typ t in
let attrs =
{
may_fail = true;
integral = Some integral;
bit_order = Some bit_order;
has_reader = false;
parser_weak_kind = WeakKindStrongPrefix;
parser_kind_nz = None
}
in
let d = decl_with_v d (Enum t i cases) in
add_global e i d (Inl attrs);
d
| Record tdnames params where fields ->
elaborate_record_decl e tdnames params where fields d.d_decl.range d.d_decl.comments d.d_exported
| CaseType tdnames params switch ->
let env = { mk_env e with this = Some tdnames.typedef_name } in
check_params env params;
let switch = check_switch check_field env switch in
let wk = weak_kind_of_switch_case env switch in
let attrs =
{
may_fail = false;
integral = None;
bit_order = None;
has_reader = false;
parser_weak_kind = wk;
parser_kind_nz = None
}
in
let d = mk_decl (CaseType tdnames params switch) d.d_decl.range d.d_decl.comments d.d_exported in
add_global e tdnames.typedef_name d (Inl attrs);
d
| OutputType out_t ->
check_output_fields e out_t.out_typ_fields;
add_output_type e out_t.out_typ_names.typedef_name d;
d
| ExternType tdnames ->
add_extern_type e tdnames.typedef_name d;
d
| ExternFn f ret params ->
let env = mk_env e in
let ret = check_typ true env ret in
check_params env params;
let d = mk_decl (ExternFn f ret params) d.d_decl.range d.d_decl.comments d.d_exported in
add_extern_fn e f d;
d
| ExternProbe i ->
add_extern_probe e i d;
d | false |
Spec.Matrix.fst | Spec.Matrix.sub | val sub:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == a.(i,j) -. b.(i,j) } | val sub:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == a.(i,j) -. b.(i,j) } | let sub #n1 #n2 a b =
map2 sub_mod a b | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 18,
"end_line": 252,
"start_col": 0,
"start_line": 251
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2)
val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2
let create n1 n2 = LSeq.create (n1 * n2) (u16 0)
val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem
let mget #n1 #n2 a i j =
index_lt n1 n2 i j;
a.[i * n2 + j]
unfold
let op_Array_Access #n1 #n2 (m:matrix n1 n2) (i,j) = mget m i j
val mset:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> v:elem
-> Pure (matrix n1 n2)
(requires True)
(ensures fun r ->
r.(i,j) == v /\ (forall i' j'. (i', j') <> (i, j) ==> r.(i', j') == a.(i',j')))
let mset #n1 #n2 a i j v =
Classical.forall_intro_2 (index_neq #n1 #n2 i j);
index_lt n1 n2 i j;
a.[i * n2 + j] <- v
unfold
let op_Array_Assignment #n1 #n2 (m:matrix n1 n2) (i,j) x = mset m i j x
val extensionality:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> Lemma
(requires forall i j. a.(i,j) == b.(i,j))
(ensures a == b)
let extensionality #n1 #n2 a b =
let aux (k:size_nat{k < n1 * n2}) : Lemma (index a k == index b k) =
let i = k / n2 in
let j = k % n2 in
div_mul_lt n2 k n1;
assert (i < n1 /\ j < n2);
index_lt n1 n2 i j;
assert (a.(i, j) == a.[i * n2 + j] /\ b.(i, j) == b.[i * n2 + j]);
assert (a.[k] == b.[k]) in
Classical.forall_intro aux;
eq_intro a b;
eq_elim a b
(*
/// Example (of course it doesn't work with Lib.IntTypes)
/// [ 0 2 ]
/// [ 1 3 ]
let m:matrix 2 2 =
assert_norm (List.length [0us; 2us; 1us; 3us] == 4);
Seq.seq_of_list [0us; 2us; 1us; 3us]
let _ = assert_norm (m.(0,0) == 0us /\ m.(1,0) == 1us /\ m.(0,1) == 2us /\ m.(1,1) == 3us)
let _ = assert_norm (let m' = m.(0,0) <- 4us in m'.(0,0) == 4us)
*)
val map:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> f:(elem -> elem)
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == f a.(i,j) }
let map #n1 #n2 f a =
let c = create n1 n2 in
Loops.repeati_inductive n1
(fun i c -> forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c.(i0,j) == f a.(i0,j))
(fun i c ->
Loops.repeati_inductive n2
(fun j c0 ->
(forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c0.(i0,j) == c.(i0,j)) /\
(forall (j0:size_nat{j0 < j}). c0.(i,j0) == f a.(i,j0)))
(fun j c' -> c'.(i,j) <- f a.(i,j))
c)
c
val mod_pow2_felem: logq:size_pos{logq < 16} -> a:elem
-> Pure elem
(requires true)
(ensures fun r -> v r == v a % pow2 logq)
let mod_pow2_felem logq a =
Math.Lemmas.pow2_lt_compat 16 logq;
mod_mask_lemma #U16 a (size logq);
assert (v (mod_mask #U16 #SEC (size logq)) == v ((u16 1 <<. size logq) -. u16 1));
a &. ((u16 1 <<. size logq) -. u16 1)
val mod_pow2:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> logq:size_pos{logq <= 16}
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. v c.(i,j) == v a.(i,j) % pow2 logq }
let mod_pow2 #n1 #n2 logq a =
if logq < 16 then
map (mod_pow2_felem logq) a
else a
val map2:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> f:(elem -> elem -> elem)
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == f a.(i,j) b.(i,j) }
let map2 #n1 #n2 f a b =
let c = create n1 n2 in
Loops.repeati_inductive n1
(fun i c -> forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c.(i0,j) == f a.(i0,j) b.(i0,j))
(fun i c ->
Loops.repeati_inductive n2
(fun j c0 ->
(forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c0.(i0,j) == c.(i0,j)) /\
(forall (j0:size_nat{j0 < j}). c0.(i,j0) == f a.(i,j0) b.(i,j0)))
(fun j c' -> c'.(i,j) <- f a.(i,j) b.(i,j))
c)
c
val add:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == a.(i,j) +. b.(i,j) }
let add #n1 #n2 a b =
map2 add_mod a b
val sub:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == a.(i,j) -. b.(i,j) } | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | a: Spec.Matrix.matrix n1 n2 -> b: Spec.Matrix.matrix n1 n2
-> c:
Spec.Matrix.matrix n1 n2
{ forall (i: Lib.IntTypes.size_nat{i < n1 /\ i < n1 /\ i < n1})
(j: Lib.IntTypes.size_nat{j < n2 /\ j < n2 /\ j < n2}).
c.(i, j) == a.(i, j) -. b.(i, j) } | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Spec.Matrix.matrix",
"Spec.Matrix.map2",
"Lib.IntTypes.sub_mod",
"Lib.IntTypes.U16",
"Lib.IntTypes.SEC",
"Prims.l_Forall",
"Prims.l_and",
"Prims.op_LessThan",
"Prims.eq2",
"Lib.IntTypes.int_t",
"Spec.Matrix.op_Array_Access",
"FStar.Pervasives.Native.Mktuple2",
"Lib.IntTypes.op_Subtraction_Dot"
] | [] | false | false | false | false | false | let sub #n1 #n2 a b =
| map2 sub_mod a b | false |
Spec.Matrix.fst | Spec.Matrix.create | val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2 | val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2 | let create n1 n2 = LSeq.create (n1 * n2) (u16 0) | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 48,
"end_line": 86,
"start_col": 0,
"start_line": 86
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2) | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | n1: Lib.IntTypes.size_nat -> n2: Lib.IntTypes.size_nat{n1 * n2 <= Lib.IntTypes.max_size_t}
-> Spec.Matrix.matrix n1 n2 | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Lib.Sequence.create",
"Spec.Matrix.elem",
"Lib.IntTypes.u16",
"Spec.Matrix.matrix"
] | [] | false | false | false | false | false | let create n1 n2 =
| LSeq.create (n1 * n2) (u16 0) | false |
Spec.Matrix.fst | Spec.Matrix.mset | val mset:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> v:elem
-> Pure (matrix n1 n2)
(requires True)
(ensures fun r ->
r.(i,j) == v /\ (forall i' j'. (i', j') <> (i, j) ==> r.(i', j') == a.(i',j'))) | val mset:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> v:elem
-> Pure (matrix n1 n2)
(requires True)
(ensures fun r ->
r.(i,j) == v /\ (forall i' j'. (i', j') <> (i, j) ==> r.(i', j') == a.(i',j'))) | let mset #n1 #n2 a i j v =
Classical.forall_intro_2 (index_neq #n1 #n2 i j);
index_lt n1 n2 i j;
a.[i * n2 + j] <- v | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 21,
"end_line": 121,
"start_col": 0,
"start_line": 118
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2)
val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2
let create n1 n2 = LSeq.create (n1 * n2) (u16 0)
val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem
let mget #n1 #n2 a i j =
index_lt n1 n2 i j;
a.[i * n2 + j]
unfold
let op_Array_Access #n1 #n2 (m:matrix n1 n2) (i,j) = mget m i j
val mset:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> v:elem
-> Pure (matrix n1 n2)
(requires True)
(ensures fun r ->
r.(i,j) == v /\ (forall i' j'. (i', j') <> (i, j) ==> r.(i', j') == a.(i',j'))) | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
a: Spec.Matrix.matrix n1 n2 ->
i: Lib.IntTypes.size_nat{i < n1} ->
j: Lib.IntTypes.size_nat{j < n2} ->
v: Spec.Matrix.elem
-> Prims.Pure (Spec.Matrix.matrix n1 n2) | Prims.Pure | [] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Spec.Matrix.matrix",
"Prims.op_LessThan",
"Spec.Matrix.elem",
"Lib.Sequence.op_String_Assignment",
"Prims.op_Addition",
"Prims.unit",
"Spec.Matrix.index_lt",
"FStar.Classical.forall_intro_2",
"Prims.nat",
"Prims.l_imp",
"Prims.op_disEquality",
"FStar.Pervasives.Native.tuple2",
"FStar.Pervasives.Native.Mktuple2",
"Prims.l_and",
"Prims.int",
"Spec.Matrix.index_neq"
] | [] | false | false | false | false | false | let mset #n1 #n2 a i j v =
| Classical.forall_intro_2 (index_neq #n1 #n2 i j);
index_lt n1 n2 i j;
a.[ i * n2 + j ] <- v | false |
Binding.fst | Binding.check_atomic_field | val check_atomic_field (env: env) (extend_scope: bool) (f: atomic_field) : ML atomic_field | val check_atomic_field (env: env) (extend_scope: bool) (f: atomic_field) : ML atomic_field | let check_atomic_field (env:env) (extend_scope: bool) (f:atomic_field)
: ML atomic_field
= let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ -> error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa = match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if
if eq_typ env sf.field_type tuint8
then true
else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE" (print_typ sf.field_type)) f.range
in
let fc = sf.field_constraint |> map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act = sf.field_action |> map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ -> error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None -> (
match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found")
p.probe_length.range
| Some i -> i
)
| Some p -> (
match GlobalEnv.resolve_probe_fn env.globals p with
| None ->
error (Printf.sprintf "Probe function %s not found" (print_ident p))
p.range
| Some i ->
i
)
in
Some { probe_fn=Some probe_fn; probe_length=length; probe_dest=dest }
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf = {
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe;
} in
let _ =
match sf.field_type.v, sf.field_array_opt,
sf.field_constraint, sf.field_bitwidth,
sf.field_action, sf.field_probe
with
| Pointer _, FieldScalar,
None, None,
None, Some _ ->
()
| _, _,
_, _,
_, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints")
f.range
| _ -> ()
in
Options.debug_print_string
(Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf } | {
"file_name": "src/3d/Binding.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 21,
"end_line": 1207,
"start_col": 0,
"start_line": 1097
} | (*
Copyright 2019 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain as copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module Binding
(*
This module implements a pass over the source AST
-- checking that all names are properly bound
-- well-typed
-- computing the size of types
-- computing which fields are dependent on others
*)
open FStar.Mul
open FStar.List.Tot
open Ast
open FStar.All
module H = Hashtable
include GlobalEnv
/// Maps locally bound names, i.e., a field name to its type
/// -- the bool signifies that this identifier has been used, and is
/// therefore marked as a dependent field
///
/// The modul_name in these ident' must be None -- TODO: add a refinement?
let local_env = H.t ident' (ident' & typ & bool)
/// `env` includes both a global and local env, together with a
/// binding for the `this` variable (bound to the name of a type) in
/// the current scope
noeq
type env = {
this: option ident;
locals: local_env;
globals: global_env;
}
let mk_env (g:global_env) =
{ this = None;
locals = H.create 10;
globals = g }
let copy_env (e:env) =
let locals = H.create 10 in
H.iter (fun k v -> H.insert locals k v) e.locals;
{
this = e.this;
globals = e.globals;
locals = locals
}
#push-options "--warn_error -272" //intentional top-level effect
let env_of_global_env
: global_env -> env
= let locals = H.create 1 in
fun g -> { this = None; locals; globals = g }
#pop-options
let global_env_of_env e = e.globals
let params_of_decl (d:decl) : list param =
match d.d_decl.v with
| ModuleAbbrev _ _
| Define _ _ _
| TypeAbbrev _ _
| Enum _ _ _ -> []
| Record _ params _ _
| CaseType _ params _ -> params
| OutputType _ -> []
| ExternType _ -> []
| ExternFn _ _ ps -> ps
| ExternProbe _ -> []
let check_shadow (e:H.t ident' 'a) (i:ident) (r:range) =
match H.try_find e i.v with
| Some j ->
let msg = Printf.sprintf "Declaration %s clashes with previous declaration" (ident_to_string i) in
error msg i.range
| _ -> ()
let typedef_names (d:decl) : option typedef_names =
match d.d_decl.v with
| Record td _ _ _
| CaseType td _ _ -> Some td
| _ -> None
let format_identifier (e:env) (i:ident) : ML ident =
let j =
match String.list_of_string i.v.name with
| [] ->
failwith "Impossible: empty identifier"
| c0::cs ->
if FStar.Char.lowercase c0 = c0
then i //it starts with a lowercase symbol; that's ok
else //otherwise, add an underscore
{i with v = {i.v with name=Ast.reserved_prefix ^ i.v.name}}
in
match H.try_find e.globals.ge_h j.v, H.try_find e.locals j.v with
| None, None -> j
| _ ->
let msg = Printf.sprintf
"This name (%s) starts will clash with another name in scope (%s) as it is translated. \
Please rename it"
(ident_to_string i) (ident_to_string j) in
error msg i.range
let add_global (e:global_env) (i:ident) (d:decl) (t:either decl_attributes macro_signature) : ML unit =
let insert k v = H.insert e.ge_h k v in
check_shadow e.ge_h i d.d_decl.range;
let env = mk_env e in
let i' = format_identifier env i in
insert i.v (d, t);
insert i'.v (d, t);
match typedef_names d with
| None -> ()
| Some td ->
if td.typedef_abbrev.v <> i.v
then begin
check_shadow e.ge_h td.typedef_abbrev d.d_decl.range;
let abbrev = format_identifier env td.typedef_abbrev in
insert td.typedef_abbrev.v (d, t);
insert abbrev.v (d, t)
end
let add_local (e:env) (i:ident) (t:typ) : ML unit =
check_shadow e.globals.ge_h i t.range;
check_shadow e.locals i t.range;
let i' = format_identifier e i in
H.insert e.locals i.v (i'.v, t, false);
H.insert e.locals i'.v (i'.v, t, false)
let try_lookup (e:env) (i:ident) : ML (option (either typ (decl & either decl_attributes macro_signature))) =
match H.try_find e.locals i.v with
| Some (_, t, true) ->
Some (Inl t)
| Some (j, t, false) -> //mark it as used
H.remove e.locals i.v;
H.insert e.locals i.v (j, t, true);
Some (Inl t)
| None ->
match H.try_find e.globals.ge_h i.v with
| Some d -> Some (Inr d)
| None -> None
let lookup (e:env) (i:ident) : ML (either typ (decl & either decl_attributes macro_signature)) =
match try_lookup e i with
| None -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
| Some v -> v
let remove_local (e:env) (i:ident) : ML unit =
match H.try_find e.locals i.v with
| Some (j, _, _) ->
H.remove e.locals i.v;
H.remove e.locals j
| _ -> ()
let resolve_record_case_output_extern_type_name (env:env) (i:ident) =
match H.try_find (global_env_of_env env).ge_out_t i.v with
| Some ({d_decl={v=OutputType ({out_typ_names=names})}}) -> names.typedef_abbrev
| _ ->
(match H.try_find (global_env_of_env env).ge_extern_t i.v with
| Some ({d_decl={v=ExternType td_names}}) -> td_names.typedef_abbrev
| _ ->
(match lookup env i with
| Inr ({d_decl={v=Record names _ _ _}}, _)
| Inr ({d_decl={v=CaseType names _ _}}, _) ->
names.typedef_name
| _ -> i))
let lookup_expr_name (e:env) (i:ident) : ML typ =
match lookup e i with
| Inl t -> t
| Inr (_, Inr ({ macro_arguments_t=[]; macro_result_t=t })) -> t
| Inr _ ->
error (Printf.sprintf "Variable %s is not an expression identifier" (ident_to_string i)) i.range
let lookup_macro_name (e:env) (i:ident) : ML macro_signature =
match lookup e i with
| Inr (_, Inr m) -> m
| _ -> error (Printf.sprintf "%s is an unknown operator" (ident_to_string i)) i.range
let lookup_macro_definition (e:env) (i:ident) =
try
let m = lookup_macro_name e i in
m.macro_defn_t
with
| _ -> None
let try_lookup_enum_cases (e:env) (i:ident)
: ML (option (list ident & typ))
= match lookup e i with
| Inr ({d_decl={v=Enum t _ tags}}, _) ->
Some (Desugar.check_desugared_enum_cases tags, t)
| _ -> None
let lookup_enum_cases (e:env) (i:ident)
: ML (list ident & typ)
= match try_lookup_enum_cases e i with
| Some (tags, t) -> tags, t
| _ -> error (Printf.sprintf "Type %s is not an enumeration" (ident_to_string i)) i.range
let is_enum (e:env) (t:typ) =
match t.v with
| Type_app i KindSpec [] ->
Some? (try_lookup_enum_cases e i)
| _ -> false
let is_used (e:env) (i:ident) : ML bool =
match H.try_find e.locals i.v with
| Some (_, t, b) -> b
| _ -> error (Printf.sprintf "Variable %s not found" (ident_to_string i)) i.range
let type_of_integer_type = function
| UInt8 -> tuint8
| UInt16 -> tuint16
| UInt32 -> tuint32
| UInt64 -> tuint64
let check_integer_bounds t i =
match t with
| UInt8 -> FStar.UInt.fits i 8
| UInt16 -> FStar.UInt.fits i 16
| UInt32 -> FStar.UInt.fits i 32
| UInt64 -> FStar.UInt.fits i 64
let type_of_constant rng (c:constant) : ML typ =
match c with
| Unit -> tunit
| Int tag i ->
if check_integer_bounds tag i
then type_of_integer_type tag
else error (Printf.sprintf "Constant %d is too large for its type %s" i (Ast.print_integer_type tag)) rng
| XInt tag _ -> //bounds checked by the syntax
type_of_integer_type tag
| Bool _ -> tbool
let parser_may_fail (env:env) (t:typ) : ML bool =
match t.v with
| Pointer _ -> true
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> attrs.may_fail
| _ -> false
let typ_is_integral env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
match lookup env hd with
| Inr (d, Inl attrs) -> Some? attrs.integral
| _ -> false
let tag_of_integral_typ env (t:typ) : ML (option _) =
match t.v with
| Pointer _ -> None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral
| _ -> None
let tag_and_bit_order_of_integral_typ env (t:typ) : ML (tag_and_bit_order: (option integer_type & option bitfield_bit_order) { Some? (snd tag_and_bit_order) ==> Some? (fst tag_and_bit_order) }) =
match t.v with
| Pointer _ -> None, None
| Type_app hd _ _ ->
match lookup env hd with
| Inr (_, Inl attrs) -> attrs.integral, attrs.bit_order
| _ -> None, None
let has_reader (env:global_env) (id:ident) : ML bool =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.has_reader
| _ -> false
let parser_kind_nz (env:global_env) (id:ident) : ML (option bool) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> attrs.parser_kind_nz
| _ -> None
let parser_weak_kind (env:global_env) (id:ident) : ML (option _) =
match H.try_find env.ge_h id.v with
| Some (_, Inl attrs) -> Some attrs.parser_weak_kind
| _ -> None
let rec typ_weak_kind env (t:typ) : ML (option weak_kind) =
match t.v with
| Pointer _ -> typ_weak_kind env tuint64
| Type_app hd _ _ -> parser_weak_kind env.globals hd
let typ_has_reader env (t:typ) : ML bool =
match t.v with
| Pointer _ -> false
| Type_app hd _ _ ->
has_reader env.globals hd
let rec unfold_typ_abbrev_only (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match try_lookup env hd with
| Some (Inr (d, _)) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_only env t
| _ -> t
end
| _ -> t
end
| _ -> t
let update_typ_abbrev (env:env) (i:ident) (t:typ)
: ML unit
= match H.try_find env.globals.ge_h i.v with
| Some (d, ms) ->
let d_decl =
match d.d_decl.v with
| TypeAbbrev _ _ -> {d.d_decl with v = TypeAbbrev t i }
| _ -> failwith "Expected a type abbreviation"
in
let d = {d with d_decl = d_decl } in
let entry = (d, ms) in
H.insert env.globals.ge_h i.v entry
| _ ->
failwith "Type abbreviation not found"
let rec unfold_typ_abbrev_and_enum (env:env) (t:typ) : ML typ =
match t.v with
| Type_app hd _ [] -> //type abbreviations are not parameterized
begin
match lookup env hd with
| Inr (d, _) ->
begin
match d.d_decl.v with
| TypeAbbrev t _ -> unfold_typ_abbrev_and_enum env t
| Enum t _ _ -> unfold_typ_abbrev_and_enum env t
| _ -> t
end
| _ -> t
end
| _ -> t
let size_of_integral_typ (env:env) (t:typ) r
: ML int
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_of_integral_typ env t with
| None -> failwith "Impossible"
| Some UInt8 -> 1
| Some UInt16 -> 2
| Some UInt32 -> 4
| Some UInt64 -> 8
let bit_order_of_integral_typ (env:env) (t:typ) r
: ML bitfield_bit_order
= let t = unfold_typ_abbrev_and_enum env t in
if not (typ_is_integral env t)
then error (Printf.sprintf "Expected and integral type, got %s"
(print_typ t))
r;
match tag_and_bit_order_of_integral_typ env t with
| _, None -> failwith "Impossible"
| _, Some order -> order
let eq_typ env t1 t2 =
if Ast.eq_typ t1 t2 then true
else Ast.eq_typ (unfold_typ_abbrev_and_enum env t1) (unfold_typ_abbrev_and_enum env t2)
let eq_typs env ts =
List.for_all (fun (t1, t2) -> eq_typ env t1 t2) ts
let cast e t t' = { e with v = App (Cast (Some t) t') [e] }
let try_cast_integer env et to : ML (option expr) =
let e, from = et in
let i_to = typ_is_integral env to in
let i_from = typ_is_integral env from in
if i_from && i_to
then
let i_from = typ_as_integer_type (unfold_typ_abbrev_and_enum env from) in
let i_to = typ_as_integer_type (unfold_typ_abbrev_and_enum env to) in
if i_from = i_to
then Some e
else if integer_type_leq i_from i_to
then Some (cast e i_from i_to)
else None
else None
let _or_ b1 b2 = b1 || b2
let _and_ b1 b2 = b1 && b2
let try_retype_arith_exprs (env:env) e1 e2 rng : ML (option (expr & expr & typ))=
let e1, t1 = e1 in
let e2, t2 = e2 in
let fail #a i : ML a = raise (Error (Printf.sprintf "(%d) Failed to retype exprs (%s : %s) and (%s : %s)"
i
(print_expr e1)
(print_typ t1)
(print_expr e2)
(print_typ t2))) in
try
let t1, t2 = unfold_typ_abbrev_and_enum env t1, unfold_typ_abbrev_and_enum env t2 in
if not (typ_is_integral env t1 `_and_`
typ_is_integral env t2)
then fail 1;
let tt1 = typ_as_integer_type t1 in
let tt2 = typ_as_integer_type t2 in
let cast e t t' = { e with v = App (Cast (Some t) t') [e] } in
let e1, e2, t =
if integer_type_leq tt1 tt2
then cast e1 tt1 tt2,
e2,
t2
else if integer_type_leq tt2 tt1
then e1,
cast e2 tt2 tt1,
t1
else fail 0
in
// FStar.IO.print_string
// (Printf.sprintf "Retyped to (%s, %s, %s)\n"
// (print_expr e1)
// (print_expr e2)
// (print_typ t));
Some (e1, e2, t)
with
| Error msg ->
FStar.IO.print_string msg;
None
| _ -> None
(*
* Add output type to the environment
*
* TODO: check_shadow
*)
let add_output_type (ge:global_env) (i:ident) (d:decl{OutputType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_out_t i d in
insert i.v;
let td_abbrev = (OutputType?._0 d.d_decl.v).out_typ_names.typedef_abbrev in
insert td_abbrev.v
(*
* Add extern type to the environment
*
* TODO: check shadow
*)
let add_extern_type (ge:global_env) (i:ident) (d:decl{ExternType? d.d_decl.v}) : ML unit =
let insert i = H.insert ge.ge_extern_t i d in
insert i.v;
let td_abbrev = (ExternType?._0 d.d_decl.v).typedef_abbrev in
insert td_abbrev.v
(*
* Add extern probe function to the environment
*
* TODO: check shadow
*)
let add_extern_probe (ge:global_env) (i:ident) (d:decl{ExternProbe? d.d_decl.v}) : ML unit =
H.insert ge.ge_probe_fn i.v d
(*
* Add extern function to the environment
*
* TODO: check shadow
*)
let add_extern_fn (ge:global_env) (i:ident) (d:decl{ExternFn? d.d_decl.v}) : ML unit =
H.insert ge.ge_extern_fn i.v d
let lookup_output_type (ge:global_env) (i:ident) : ML out_typ =
match H.try_find ge.ge_out_t i.v with
| Some ({d_decl={v=OutputType out_t}}) -> out_t
| _ -> error (Printf.sprintf "Cannot find output type %s" (ident_to_string i)) i.range
(*
* Returns the type of the field, with optional bitwidth if the field is a bitfield
*)
let lookup_output_type_field (ge:global_env) (i f:ident) : ML (typ & option int) =
let out_t = lookup_output_type ge i in
let rec find (flds:list out_field) : (option (typ & option int)) =
match flds with
| [] -> None
| (Out_field_named f' t n)::tl ->
if eq_idents f f' then Some (t, n)
else find tl
| (Out_field_anon l _)::tl ->
(match find l with
| None -> find tl
| Some t -> Some t) in
match find out_t.out_typ_fields with
| Some t -> t
| None ->
error (Printf.sprintf "Cannot find output field %s:%s" (ident_to_string i) (ident_to_string f)) f.range
let lookup_extern_type (ge:global_env) (i:ident) : ML unit =
match H.try_find ge.ge_extern_t i.v with
| Some ({d_decl={v=ExternType _}}) -> ()
| _ -> error (Printf.sprintf "Cannot find declaration for extern type %s" (ident_to_string i)) i.range
let lookup_extern_fn (ge:global_env) (f:ident) : ML (typ & list param) =
match H.try_find ge.ge_extern_fn f.v with
| Some ({d_decl={v=ExternFn _ ret ps}}) -> ret, ps
| _ -> error (Printf.sprintf "Cannot find declaration for extern function %s" (ident_to_string f)) f.range
let check_output_type (ge:global_env) (t:typ) : ML ident =
let err () : ML ident =
error (Printf.sprintf "Type %s is not an output type" (print_typ t)) t.range in
match t.v with
| Type_app i KindOutput [] -> i
| _ -> err ()
/// Populated the output expression metadata
///
/// We enforce that the spec cannot take address of output type bitfields
let rec check_out_expr (env:env) (oe0:out_expr)
: ML (oe:out_expr{Some? oe.out_expr_meta}) =
match oe0.out_expr_node.v with
| OE_id i ->
let t = lookup_expr_name env i in
{oe0 with
out_expr_meta = Some ({
out_expr_base_t = t;
out_expr_t = t;
out_expr_bit_width = None})}
| OE_star oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_star oe};
out_expr_meta=Some ({ out_expr_base_t = oe_bt;
out_expr_t = t;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_addrof oe ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_addrof oe};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = with_range (Pointer oe_t) oe.out_expr_node.range;
out_expr_bit_width = None })}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
| OE_deref oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match oe_t.v, bopt with
| Pointer t, None ->
let i = check_output_type (global_env_of_env env) t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_deref oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Output expression %s is ill-typed since base type %s is not a pointer type"
(print_out_expr oe0) (print_typ oe_t)) oe.out_expr_node.range)
| OE_dot oe f ->
let oe = check_out_expr env oe in
let { out_expr_base_t = oe_bt;
out_expr_t = oe_t;
out_expr_bit_width = bopt } = Some?.v oe.out_expr_meta in
(match bopt with
| None ->
let i = check_output_type (global_env_of_env env) oe_t in
let out_expr_t, out_expr_bit_width = lookup_output_type_field
(global_env_of_env env)
i f in
{oe0 with
out_expr_node={oe0.out_expr_node with v=OE_dot oe f};
out_expr_meta=Some ({
out_expr_base_t = oe_bt;
out_expr_t = out_expr_t;
out_expr_bit_width = out_expr_bit_width})}
| _ ->
error
(Printf.sprintf "Cannot take address of a bit field %s"
(print_out_expr oe0)) oe.out_expr_node.range)
let range_of_typ_param (p:typ_param) = match p with
| Inl e -> e.range
| Inr p -> p.out_expr_node.range
#push-options "--z3rlimit_factor 4"
let rec check_typ (pointer_ok:bool) (env:env) (t:typ)
: ML typ
= match t.v with
| Pointer t0 ->
if pointer_ok
then { t with v = Pointer (check_typ pointer_ok env t0) }
else error (Printf.sprintf "Pointer types are not permissible here; got %s" (print_typ t)) t.range
| Type_app s KindSpec ps ->
(match lookup env s with
| Inl _ ->
error (Printf.sprintf "%s is not a type" (ident_to_string s)) s.range
| Inr (d, _) ->
let params = params_of_decl d in
if List.length params <> List.length ps
then error (Printf.sprintf "Not enough arguments to %s" (ident_to_string s)) s.range;
let ps =
List.map2 (fun (t, _, _) p ->
let p, t' = check_typ_param env p in
if not (eq_typ env t t')
then begin
match p with
| Inl e -> (match try_cast_integer env (e, t') t with
| Some e -> Inl e
| _ -> error "Argument type mismatch after trying integer cast" (range_of_typ_param p))
| _ ->
error (Printf.sprintf
"Argument type mismatch (%s vs %s)"
(Ast.print_typ t) (Ast.print_typ t')) (range_of_typ_param p)
end
else p)
params
ps
in
{t with v = Type_app s KindSpec ps})
| Type_app i KindExtern args ->
if List.length args <> 0
then error (Printf.sprintf "Cannot apply the extern type %s" (ident_to_string i)) i.range
else t
| Type_app _ KindOutput _ ->
error "Impossible, check_typ is not supposed to typecheck output types!" t.range
and check_ident (env:env) (i:ident)
: ML (ident & typ)
= let t = lookup_expr_name env i in
i, t
and check_expr (env:env) (e:expr)
: ML (expr & typ)
= let w e' = with_range e' e.range in
let arith_op_t op t : ML Ast.op =
let t = tag_of_integral_typ env t in
match op with
| Plus _ -> Plus t
| Minus _ -> Minus t
| Mul _ -> Mul t
| Division _ -> Division t
| Remainder _ -> Remainder t
| BitwiseNot _ -> BitwiseNot t
| BitwiseAnd _ -> BitwiseAnd t
| BitwiseOr _ -> BitwiseOr t
| BitwiseXor _ -> BitwiseXor t
| ShiftLeft _ -> ShiftLeft t
| ShiftRight _ -> ShiftRight t
| LE _ -> LE t
| LT _ -> LT t
| GE _ -> GE t
| GT _ -> GT t
| _ -> op
in
match e.v with
| Constant c ->
e, type_of_constant e.range c
| Identifier i ->
let i, t = check_ident env i in
{ e with v = Identifier i }, t
| Static _ ->
failwith "Static expressions should have been desugared already"
| This ->
error "`this` is not a valid expression" e.range
| App (Cast _ to) [n] ->
let n, from = check_expr env n in
begin
if not (typ_is_integral env from)
then error (Printf.sprintf "Casts are only supported on integral types; %s is not integral"
(print_typ from)) e.range
else match from.v with
| Type_app i KindSpec _ ->
let from_t = as_integer_typ i in
// if integer_type_lub to from_t <> to
// then error (Printf.sprintf "Only widening casts are supported; casting %s to %s loses precision"
// (print_typ from)
// (print_integer_type to))
// e.range
// else
let e = {e with v = App (Cast (Some from_t) to) [n]} in
let t = type_of_integer_type to in
Options.debug_print_string
(Printf.sprintf "--------------- %s has type %s\n" (print_expr e) (print_typ t));
e, t
| _ -> failwith "Impossible: must be an integral type"
end
| App SizeOf [{v=This;range=r}] ->
let e =
match env.this with
| None ->
error "`this` is not in scope" r
| Some i ->
with_range (App SizeOf [with_range (Identifier i) r]) e.range
in
e, tuint32
| App SizeOf [{v=Identifier i;range=r}] ->
begin
match lookup env i with
| Inr ({d_decl={v=Enum _ _ _}}, _)
| Inr ({d_decl={v=Record _ _ _ _ }}, _)
| Inr ({d_decl={v=CaseType _ _ _}}, _)
| Inr (_, Inl _) -> //has decl-attributes
e, tuint32
| _ ->
error "`sizeof` applied to a non-sized-typed" r
end
| App (Ext s) es ->
//TODO: AR: not sure about this Ext node
let m = lookup_macro_name env (with_range (to_ident' s) e.range) in
let n_formals = List.length m.macro_arguments_t in
let n_actuals = List.length es in
if n_formals <> n_actuals
then error (Printf.sprintf "%s expects %d arguments; got %d" s n_formals n_actuals) e.range;
let check_arg e t : ML expr =
let e, t' = check_expr env e in
if not (eq_typ env t t')
then error
(Printf.sprintf
"%s expected argument of type %s; \
got argument %s of type %s"
s (print_typ t) (print_expr e) (print_typ t))
e.range;
e
in
let es = List.map2 check_arg es m.macro_arguments_t in
with_range (App (Ext s) es) e.range,
m.macro_result_t
| App op es ->
let ets = List.map (check_expr env) es in
match ets with
| [(e1, t1)] ->
begin
match op with
| Not ->
if not (eq_typ env t1 tbool)
then error "Expected bool" e1.range;
w (App Not [e1]), t1
| BitwiseNot _ ->
if typ_is_integral env t1
then w (App (arith_op_t op t1) [e1]), t1
else error (Printf.sprintf "Bitwise negation is only available on integral types; got %s"
(print_typ t1))
e1.range
| _ ->
error "Not a unary op" e1.range
end
| [(e1,t1);(e2,t2)] ->
begin
match op with
| Eq
| Neq ->
if not (eq_typ env t1 t2)
then
begin
let err #a () : ML a =
error
(Printf.sprintf "Equality on unequal types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range
in
let it1 = typ_is_integral env t1 in
let it2 = typ_is_integral env t2 in
if it1 && it2
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) -> w (App op [e1; e2]), tbool
| _ -> err ()
else err ()
end
else
w (App op [e1; e2]), tbool
| And
| Or ->
if not (eq_typs env [(t1,tbool); (t2,tbool)])
then error "Binary boolean op on non booleans" e.range;
w (App op [e1; e2]), tbool
| ShiftLeft _
| ShiftRight _ ->
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Bit shifts are only permissible on integral types: got %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
begin
match try_cast_integer env (e2, t2) tuint32 with
| None ->
error (Printf.sprintf "Bit shift offset is too large: got type %s"
(print_typ t2))
e2.range
| Some e2 ->
w (App (arith_op_t op t1) [e1; e2]), t1
end
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| LT _
| GT _
| LE _
| GE _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _ ->
let result_typ t =
match op with
| LT _ | GT _ | LE _ | GE _ -> tbool
| _ -> t
in
let t1_integral = typ_is_integral env t1 in
let t2_integral = typ_is_integral env t2 in
if not t1_integral || not t2_integral
then error (Printf.sprintf "Binary integer op on non-integral types: %s and %s"
(print_typ t1)
(print_typ t2))
e.range;
if not (eq_typs env [(t1,t2)])
then match try_retype_arith_exprs env (e1, t1) (e2, t2) e.range with
| Some (e1, e2, t) ->
w (App (arith_op_t op t) [e1; e2]), result_typ t
| _ ->
error (Printf.sprintf "Binary integer operator (%s) on non-equal types: %s and %s"
(print_expr e)
(print_typ t1)
(print_typ t2))
e.range
else w (App (arith_op_t op t1) [e1; e2]), result_typ t1
| _ ->
error "Not a binary op" e.range
end
| [(e1, t1); (e2, t2); (e3, t3)] ->
begin
match op with
| IfThenElse ->
if not (eq_typ env t1 tbool)
then error (Printf.sprintf "If-then-else expects a boolean guard, got %s" (print_typ t1))
e1.range;
if not (eq_typ env t2 t3)
then match try_retype_arith_exprs env (e2, t2) (e3, t3) e.range with
| Some (e2, e3, t) ->
w (App IfThenElse [e1;e2;e3]), t
| None ->
error (Printf.sprintf "then- and else-branch do not have the same type: got %s and %s"
(print_typ t2)
(print_typ t3))
e.range
else
w (App IfThenElse [e1;e2;e3]), t2
| BitFieldOf n order ->
let base_size = size_of_integral_typ env t1 e1.range in
let size = 8 * base_size in
if n <> size
then error
(Printf.sprintf "BitFieldOf size %d is not equal to %d, i.e., the bit size %s"
n size (print_expr e1))
e1.range;
begin
match e2.v, e3.v with
| Constant (Int UInt32 from), (Constant (Int UInt32 to)) ->
if not
(from <= size
&& from <= to
&& to <= size)
then error "bitfield-of expresssions is out of bounds" e.range;
w (App (BitFieldOf n order) [e1; e2; e3]), t1
| _ ->
error "bitfield-of with non-32-bit-consant indices" e.range
end
| _ ->
error "Unexpected arity" e.range
end
| _ -> error "Unexpected arity" e.range
and check_typ_param (env:env) (p:typ_param) : ML (typ_param & typ) =
match p with
| Inl e ->
let e, t = check_expr env e in
Inl e, t
| Inr o ->
let o = check_out_expr env o in
let { out_expr_t = t;
out_expr_bit_width = bopt } = Some?.v o.out_expr_meta in
(match bopt with
| None ->
Inr o, t
| _ ->
error ("Type parameter cannot be a bitfield") (range_of_typ_param p))
#pop-options
#push-options "--z3rlimit_factor 3"
let rec check_field_action (env:env) (f:atomic_field) (a:action)
: ML (action & typ)
= let check_atomic_action env (r:range) (a:atomic_action)
: ML (atomic_action & typ)
= match a with
| Action_return e ->
let e, t = check_expr env e in
Action_return e, t
| Action_abort ->
Action_abort, tunit
| Action_field_pos_64 ->
Action_field_pos_64, tuint64
| Action_field_pos_32 ->
Action_field_pos_32, tuint32
| Action_field_ptr ->
Action_field_ptr, puint8
| Action_field_ptr_after e write_to ->
let e, t = check_expr env e in
if not (eq_typ env t tuint64)
then
error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ tuint64)
(Ast.print_expr e)
(Ast.print_typ t)) e.range
else
let write_to = check_out_expr env write_to in
let { out_expr_t = et } = Some?.v write_to.out_expr_meta in
if not (eq_typ env et puint8)
then
error (Printf.sprintf "Pointee type mismatch, expected %s whereas %s points to %s"
(Ast.print_typ puint8)
(Ast.print_out_expr write_to)
(Ast.print_typ et)) write_to.out_expr_node.range
else
Action_field_ptr_after e write_to, tbool
| Action_deref i ->
let t = lookup_expr_name env i in
begin
match t.v with
| Pointer t -> Action_deref i, t
| _ -> error "Dereferencing a non-pointer" i.range
end
| Action_assignment lhs rhs ->
let lhs = check_out_expr env lhs in
let { out_expr_t = t } = Some?.v lhs.out_expr_meta in
let rhs, t' = check_expr env rhs in
let def_ret = Action_assignment lhs rhs, tunit in
if not (eq_typ env t t')
then begin
match try_cast_integer env (rhs, t') t with
| Some rhs ->
Action_assignment lhs rhs, tunit
| None ->
warning (Printf.sprintf
"Assigning to %s of type %s a value of incompatible type %s"
(print_out_expr lhs)
(print_typ t)
(print_typ t'))
rhs.range;
def_ret
end
else def_ret
| Action_call f args ->
let ret_t, params = lookup_extern_fn (global_env_of_env env) f in
if List.length params <> List.length args
then error (Printf.sprintf "Insufficient arguments to extern function %s" (ident_to_string f)) f.range
else let args = List.map2 (fun (t, _, _) arg ->
let arg, t_arg = check_expr env arg in
if not (eq_typ env t t_arg)
then error (Printf.sprintf "Argument type mismatch, expected %s whereas %s has type %s"
(Ast.print_typ t)
(Ast.print_expr arg)
(Ast.print_typ t_arg)) arg.range
else arg) params args in
Action_call f args, tunit
in
match a.v with
| Atomic_action aa ->
let aa, t = check_atomic_action env a.range aa in
{ a with v=Atomic_action aa }, t
| Action_seq a0 rest ->
let a0, _ = check_atomic_action env a.range a0 in
let rest, t = check_field_action env f rest in
{ a with v=Action_seq a0 rest }, t
| Action_ite hd then_ else_ ->
let hd, t = check_expr env hd in
if not (eq_typ env t tbool)
then error (Printf.sprintf
"Branching is only permitted on boolean expressions, %s has type %s"
(print_expr hd)
(print_typ t))
hd.range;
let then_, t = check_field_action env f then_ in
let else_, t' =
match else_ with
| None -> None, tunit
| Some else_ ->
let else_, t = check_field_action env f else_ in
Some else_, t
in
let branches_eq_t = eq_typ env t t' in
let eq_t_unit = eq_typ env t tunit in
if not branches_eq_t
|| (None? else_ && not eq_t_unit)
then error (Printf.sprintf "The branches of a conditional must both have the same type; got %s and %s"
(print_typ t)
(print_typ t'))
a.range;
{ a with v = Action_ite hd then_ else_ }, t
| Action_let i aa k ->
let aa, t = check_atomic_action env a.range aa in
add_local env i t;
let k, t = check_field_action env f k in
remove_local env i;
{ a with v = Action_let i aa k }, t
| Action_act a ->
let a, t = check_field_action env f a in
if eq_typ env t tunit
then { a with v = Action_act a }, tbool
else error (Printf.sprintf "This ':act' action returns %s instead of unit"
(print_typ t))
a.range
#pop-options | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"GlobalEnv.fst.checked",
"FStar.UInt.fsti.checked",
"FStar.String.fsti.checked",
"FStar.ST.fst.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.IO.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Desugar.fst.checked",
"Deps.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Binding.fst"
} | [
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.List.Tot",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "GlobalEnv",
"short_module": null
},
{
"abbrev": false,
"full_module": "Ast",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | env: Binding.env -> extend_scope: Prims.bool -> f: Ast.atomic_field -> FStar.All.ML Ast.atomic_field | FStar.All.ML | [
"ml"
] | [] | [
"Binding.env",
"Prims.bool",
"Ast.atomic_field",
"Ast.Mkwith_meta_t",
"Ast.atomic_field'",
"Ast.__proj__Mkwith_meta_t__item__range",
"Ast.__proj__Mkwith_meta_t__item__comments",
"Prims.unit",
"Options.debug_print_string",
"FStar.Printf.sprintf",
"Ast.print_ident",
"Ast.__proj__Mkatomic_field'__item__field_ident",
"FStar.String.concat",
"FStar.Pervasives.Native.Mktuple6",
"Ast.typ'",
"Ast.field_array_t",
"FStar.Pervasives.Native.option",
"Ast.expr",
"Ast.field_bitwidth_t",
"FStar.Pervasives.Native.tuple2",
"Ast.action",
"Ast.probe_call",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.__proj__Mkatomic_field'__item__field_type",
"Ast.__proj__Mkatomic_field'__item__field_array_opt",
"Ast.__proj__Mkatomic_field'__item__field_constraint",
"Ast.__proj__Mkatomic_field'__item__field_bitwidth",
"Ast.__proj__Mkatomic_field'__item__field_action",
"Ast.__proj__Mkatomic_field'__item__field_probe",
"Ast.with_meta_t",
"Ast.error",
"FStar.Pervasives.Native.tuple6",
"Ast.Mkatomic_field'",
"Ast.__proj__Mkatomic_field'__item__field_dependence",
"Binding.add_local",
"FStar.Pervasives.Native.None",
"Ast.typ",
"Ast.ident",
"FStar.Pervasives.Native.Some",
"Ast.Mkprobe_call",
"Ast.__proj__Mkprobe_call__item__probe_fn",
"Ast.expr'",
"Ast.__proj__Mkprobe_call__item__probe_length",
"GlobalEnv.default_probe_fn",
"Binding.__proj__Mkenv__item__globals",
"Ast.ident'",
"GlobalEnv.resolve_probe_fn",
"Prims.string",
"Ast.print_typ",
"Prims.op_Negation",
"Binding.eq_typ",
"Ast.tcopybuffer",
"Binding.check_ident",
"Ast.__proj__Mkprobe_call__item__probe_dest",
"Ast.print_expr",
"Binding.try_cast_integer",
"FStar.Pervasives.Native.Mktuple2",
"Ast.tuint64",
"Binding.check_expr",
"Ast.map_opt",
"Binding.remove_local",
"Binding.is_used",
"Binding.check_field_action",
"FStar.Pervasives.Native.fst",
"Ast.FieldScalar",
"Ast.array_qualifier",
"Ast.FieldArrayQualified",
"Ast.FieldString",
"Ast.FieldConsumeAll",
"Ast.tuint8be",
"Ast.tuint8",
"Ast.tuint32",
"Binding.check_typ",
"FStar.Pervasives.Native.uu___is_Some"
] | [] | false | true | false | false | false | let check_atomic_field (env: env) (extend_scope: bool) (f: atomic_field) : ML atomic_field =
| let sf = f.v in
let sf_field_type = check_typ (Some? sf.field_probe) env sf.field_type in
let check_annot (e: expr) : ML expr =
let e, t = check_expr env e in
if not (eq_typ env t tuint32)
then
match try_cast_integer env (e, t) tuint32 with
| Some e -> e
| _ ->
error (Printf.sprintf "Array expression %s has type %s instead of UInt32"
(print_expr e)
(print_typ t))
e.range
else e
in
let fa =
match sf.field_array_opt with
| FieldScalar -> FieldScalar
| FieldArrayQualified (e, b) -> FieldArrayQualified (check_annot e, b)
| FieldString sz -> FieldString (map_opt check_annot sz)
| FieldConsumeAll ->
if if eq_typ env sf.field_type tuint8 then true else eq_typ env sf.field_type tuint8be
then FieldConsumeAll
else
error (Printf.sprintf "This ':consume-all field returns %s instead of UINT8 or UINT8BE"
(print_typ sf.field_type))
f.range
in
let fc =
sf.field_constraint |>
map_opt (fun e ->
add_local env sf.field_ident sf.field_type;
let e = fst (check_expr env e) in
remove_local env sf.field_ident;
e)
in
let f_act =
sf.field_action |>
map_opt (fun (a, _) ->
add_local env sf.field_ident sf.field_type;
let a, _ = check_field_action env f a in
let dependent = is_used env sf.field_ident in
remove_local env sf.field_ident;
a, dependent)
in
let f_probe =
match sf.field_probe with
| None -> None
| Some p ->
let length, typ = check_expr env p.probe_length in
let length =
if not (eq_typ env typ tuint64)
then
match try_cast_integer env (length, typ) tuint64 with
| Some e -> e
| _ ->
error (Printf.sprintf "Probe length expression %s has type %s instead of UInt64"
(print_expr length)
(print_typ typ))
length.range
else length
in
let dest, dest_typ = check_ident env p.probe_dest in
if not (eq_typ env dest_typ tcopybuffer)
then
error (Printf.sprintf "Probe destination expression %s has type %s instead of EVERPARSE_COPY_BUFFER_T"
(print_ident dest)
(print_typ dest_typ))
dest.range;
let probe_fn =
match p.probe_fn with
| None ->
(match GlobalEnv.default_probe_fn env.globals with
| None ->
error (Printf.sprintf "Probe function not specified and no default probe function found"
)
p.probe_length.range
| Some i -> i)
| Some p ->
(match GlobalEnv.resolve_probe_fn env.globals p with
| None -> error (Printf.sprintf "Probe function %s not found" (print_ident p)) p.range
| Some i -> i)
in
Some ({ probe_fn = Some probe_fn; probe_length = length; probe_dest = dest })
in
if extend_scope then add_local env sf.field_ident sf.field_type;
let sf =
{
sf with
field_type = sf_field_type;
field_array_opt = fa;
field_constraint = fc;
field_action = f_act;
field_probe = f_probe
}
in
let _ =
match
sf.field_type.v,
sf.field_array_opt,
sf.field_constraint,
sf.field_bitwidth,
sf.field_action,
sf.field_probe
with
| Pointer _, FieldScalar, None, None, None, Some _ -> ()
| _, _, _, _, _, Some _ ->
error (Printf.sprintf "Probe annotation is only allowed on pointer fields with no other constraints"
)
f.range
| _ -> ()
in
Options.debug_print_string (Printf.sprintf "Field %s has comments <%s>\n"
(print_ident sf.field_ident)
(String.concat "\n" f.comments));
{ f with v = sf } | false |
Spec.Matrix.fst | Spec.Matrix.add | val add:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == a.(i,j) +. b.(i,j) } | val add:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == a.(i,j) +. b.(i,j) } | let add #n1 #n2 a b =
map2 add_mod a b | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 18,
"end_line": 241,
"start_col": 0,
"start_line": 240
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2)
val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2
let create n1 n2 = LSeq.create (n1 * n2) (u16 0)
val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem
let mget #n1 #n2 a i j =
index_lt n1 n2 i j;
a.[i * n2 + j]
unfold
let op_Array_Access #n1 #n2 (m:matrix n1 n2) (i,j) = mget m i j
val mset:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> v:elem
-> Pure (matrix n1 n2)
(requires True)
(ensures fun r ->
r.(i,j) == v /\ (forall i' j'. (i', j') <> (i, j) ==> r.(i', j') == a.(i',j')))
let mset #n1 #n2 a i j v =
Classical.forall_intro_2 (index_neq #n1 #n2 i j);
index_lt n1 n2 i j;
a.[i * n2 + j] <- v
unfold
let op_Array_Assignment #n1 #n2 (m:matrix n1 n2) (i,j) x = mset m i j x
val extensionality:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> Lemma
(requires forall i j. a.(i,j) == b.(i,j))
(ensures a == b)
let extensionality #n1 #n2 a b =
let aux (k:size_nat{k < n1 * n2}) : Lemma (index a k == index b k) =
let i = k / n2 in
let j = k % n2 in
div_mul_lt n2 k n1;
assert (i < n1 /\ j < n2);
index_lt n1 n2 i j;
assert (a.(i, j) == a.[i * n2 + j] /\ b.(i, j) == b.[i * n2 + j]);
assert (a.[k] == b.[k]) in
Classical.forall_intro aux;
eq_intro a b;
eq_elim a b
(*
/// Example (of course it doesn't work with Lib.IntTypes)
/// [ 0 2 ]
/// [ 1 3 ]
let m:matrix 2 2 =
assert_norm (List.length [0us; 2us; 1us; 3us] == 4);
Seq.seq_of_list [0us; 2us; 1us; 3us]
let _ = assert_norm (m.(0,0) == 0us /\ m.(1,0) == 1us /\ m.(0,1) == 2us /\ m.(1,1) == 3us)
let _ = assert_norm (let m' = m.(0,0) <- 4us in m'.(0,0) == 4us)
*)
val map:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> f:(elem -> elem)
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == f a.(i,j) }
let map #n1 #n2 f a =
let c = create n1 n2 in
Loops.repeati_inductive n1
(fun i c -> forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c.(i0,j) == f a.(i0,j))
(fun i c ->
Loops.repeati_inductive n2
(fun j c0 ->
(forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c0.(i0,j) == c.(i0,j)) /\
(forall (j0:size_nat{j0 < j}). c0.(i,j0) == f a.(i,j0)))
(fun j c' -> c'.(i,j) <- f a.(i,j))
c)
c
val mod_pow2_felem: logq:size_pos{logq < 16} -> a:elem
-> Pure elem
(requires true)
(ensures fun r -> v r == v a % pow2 logq)
let mod_pow2_felem logq a =
Math.Lemmas.pow2_lt_compat 16 logq;
mod_mask_lemma #U16 a (size logq);
assert (v (mod_mask #U16 #SEC (size logq)) == v ((u16 1 <<. size logq) -. u16 1));
a &. ((u16 1 <<. size logq) -. u16 1)
val mod_pow2:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> logq:size_pos{logq <= 16}
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. v c.(i,j) == v a.(i,j) % pow2 logq }
let mod_pow2 #n1 #n2 logq a =
if logq < 16 then
map (mod_pow2_felem logq) a
else a
val map2:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> f:(elem -> elem -> elem)
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == f a.(i,j) b.(i,j) }
let map2 #n1 #n2 f a b =
let c = create n1 n2 in
Loops.repeati_inductive n1
(fun i c -> forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c.(i0,j) == f a.(i0,j) b.(i0,j))
(fun i c ->
Loops.repeati_inductive n2
(fun j c0 ->
(forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c0.(i0,j) == c.(i0,j)) /\
(forall (j0:size_nat{j0 < j}). c0.(i,j0) == f a.(i,j0) b.(i,j0)))
(fun j c' -> c'.(i,j) <- f a.(i,j) b.(i,j))
c)
c
val add:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == a.(i,j) +. b.(i,j) } | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | a: Spec.Matrix.matrix n1 n2 -> b: Spec.Matrix.matrix n1 n2
-> c:
Spec.Matrix.matrix n1 n2
{ forall (i: Lib.IntTypes.size_nat{i < n1 /\ i < n1 /\ i < n1})
(j: Lib.IntTypes.size_nat{j < n2 /\ j < n2 /\ j < n2}).
c.(i, j) == a.(i, j) +. b.(i, j) } | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Spec.Matrix.matrix",
"Spec.Matrix.map2",
"Lib.IntTypes.add_mod",
"Lib.IntTypes.U16",
"Lib.IntTypes.SEC",
"Prims.l_Forall",
"Prims.l_and",
"Prims.op_LessThan",
"Prims.eq2",
"Lib.IntTypes.int_t",
"Spec.Matrix.op_Array_Access",
"FStar.Pervasives.Native.Mktuple2",
"Lib.IntTypes.op_Plus_Dot"
] | [] | false | false | false | false | false | let add #n1 #n2 a b =
| map2 add_mod a b | false |
Spec.Matrix.fst | Spec.Matrix.index_neq | val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2)) | val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2)) | let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
} | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 7,
"end_line": 74,
"start_col": 0,
"start_line": 46
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2)) | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
i: Lib.IntTypes.size_nat{i < n1} ->
j: Prims.nat{j < n2} ->
i': Prims.nat{i' < n1} ->
j': Prims.nat{j' < n2}
-> FStar.Pervasives.Lemma
(ensures (i', j') <> (i, j) ==> i' * n2 + j' <> i * n2 + j /\ i' * n2 + j' < n1 * n2) | FStar.Pervasives.Lemma | [
"lemma"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Prims.op_LessThan",
"Prims.nat",
"FStar.Calc.calc_finish",
"Prims.int",
"Prims.op_Addition",
"Prims.Cons",
"FStar.Preorder.relation",
"Prims.eq2",
"Prims.Nil",
"Prims.unit",
"FStar.Calc.calc_step",
"FStar.Calc.calc_init",
"FStar.Calc.calc_pack",
"Prims.squash",
"FStar.Math.Lemmas.distributivity_add_left",
"FStar.Math.Lemmas.lemma_mult_le_right",
"Prims.bool",
"Prims.op_Equality",
"Prims.l_or",
"Prims.l_and",
"Prims._assert",
"Spec.Matrix.index_lt"
] | [] | false | false | true | false | false | let index_neq #n1 #n2 i j i' j' =
| index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i
then
calc ( < ) {
i' * n2 + j';
( < ) { () }
i' * n2 + n2;
( == ) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
( <= ) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
( <= ) { () }
i * n2 + j;
}
else
if i = i'
then ()
else
calc ( < ) {
i * n2 + j;
( < ) { () }
i * n2 + n2;
( == ) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
( <= ) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
( <= ) { () }
i' * n2 + j';
} | false |
Spec.Matrix.fst | Spec.Matrix.mod_pow2_felem | val mod_pow2_felem: logq:size_pos{logq < 16} -> a:elem
-> Pure elem
(requires true)
(ensures fun r -> v r == v a % pow2 logq) | val mod_pow2_felem: logq:size_pos{logq < 16} -> a:elem
-> Pure elem
(requires true)
(ensures fun r -> v r == v a % pow2 logq) | let mod_pow2_felem logq a =
Math.Lemmas.pow2_lt_compat 16 logq;
mod_mask_lemma #U16 a (size logq);
assert (v (mod_mask #U16 #SEC (size logq)) == v ((u16 1 <<. size logq) -. u16 1));
a &. ((u16 1 <<. size logq) -. u16 1) | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 39,
"end_line": 195,
"start_col": 0,
"start_line": 191
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2)
val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2
let create n1 n2 = LSeq.create (n1 * n2) (u16 0)
val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem
let mget #n1 #n2 a i j =
index_lt n1 n2 i j;
a.[i * n2 + j]
unfold
let op_Array_Access #n1 #n2 (m:matrix n1 n2) (i,j) = mget m i j
val mset:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> v:elem
-> Pure (matrix n1 n2)
(requires True)
(ensures fun r ->
r.(i,j) == v /\ (forall i' j'. (i', j') <> (i, j) ==> r.(i', j') == a.(i',j')))
let mset #n1 #n2 a i j v =
Classical.forall_intro_2 (index_neq #n1 #n2 i j);
index_lt n1 n2 i j;
a.[i * n2 + j] <- v
unfold
let op_Array_Assignment #n1 #n2 (m:matrix n1 n2) (i,j) x = mset m i j x
val extensionality:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> Lemma
(requires forall i j. a.(i,j) == b.(i,j))
(ensures a == b)
let extensionality #n1 #n2 a b =
let aux (k:size_nat{k < n1 * n2}) : Lemma (index a k == index b k) =
let i = k / n2 in
let j = k % n2 in
div_mul_lt n2 k n1;
assert (i < n1 /\ j < n2);
index_lt n1 n2 i j;
assert (a.(i, j) == a.[i * n2 + j] /\ b.(i, j) == b.[i * n2 + j]);
assert (a.[k] == b.[k]) in
Classical.forall_intro aux;
eq_intro a b;
eq_elim a b
(*
/// Example (of course it doesn't work with Lib.IntTypes)
/// [ 0 2 ]
/// [ 1 3 ]
let m:matrix 2 2 =
assert_norm (List.length [0us; 2us; 1us; 3us] == 4);
Seq.seq_of_list [0us; 2us; 1us; 3us]
let _ = assert_norm (m.(0,0) == 0us /\ m.(1,0) == 1us /\ m.(0,1) == 2us /\ m.(1,1) == 3us)
let _ = assert_norm (let m' = m.(0,0) <- 4us in m'.(0,0) == 4us)
*)
val map:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> f:(elem -> elem)
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == f a.(i,j) }
let map #n1 #n2 f a =
let c = create n1 n2 in
Loops.repeati_inductive n1
(fun i c -> forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c.(i0,j) == f a.(i0,j))
(fun i c ->
Loops.repeati_inductive n2
(fun j c0 ->
(forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c0.(i0,j) == c.(i0,j)) /\
(forall (j0:size_nat{j0 < j}). c0.(i,j0) == f a.(i,j0)))
(fun j c' -> c'.(i,j) <- f a.(i,j))
c)
c
val mod_pow2_felem: logq:size_pos{logq < 16} -> a:elem
-> Pure elem
(requires true)
(ensures fun r -> v r == v a % pow2 logq) | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | logq: Lib.IntTypes.size_pos{logq < 16} -> a: Spec.Matrix.elem -> Prims.Pure Spec.Matrix.elem | Prims.Pure | [] | [] | [
"Lib.IntTypes.size_pos",
"Prims.b2t",
"Prims.op_LessThan",
"Spec.Matrix.elem",
"Lib.IntTypes.op_Amp_Dot",
"Lib.IntTypes.U16",
"Lib.IntTypes.SEC",
"Lib.IntTypes.op_Subtraction_Dot",
"Lib.IntTypes.op_Less_Less_Dot",
"Lib.IntTypes.u16",
"Lib.IntTypes.size",
"Prims.unit",
"Prims._assert",
"Prims.eq2",
"Lib.IntTypes.range_t",
"Lib.IntTypes.v",
"Lib.IntTypes.mod_mask",
"Lib.IntTypes.mod_mask_lemma",
"FStar.Math.Lemmas.pow2_lt_compat"
] | [] | false | false | false | false | false | let mod_pow2_felem logq a =
| Math.Lemmas.pow2_lt_compat 16 logq;
mod_mask_lemma #U16 a (size logq);
assert (v (mod_mask #U16 #SEC (size logq)) == v ((u16 1 <<. size logq) -. u16 1));
a &. ((u16 1 <<. size logq) -. u16 1) | false |
Spec.Matrix.fst | Spec.Matrix.sum | val sum : f: (j: Lib.IntTypes.size_nat{j < n} -> Prims.GTot Lib.IntTypes.uint16)
-> Prims.GTot Lib.IntTypes.uint16 | let sum #n f = sum_ #n f n | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 26,
"end_line": 266,
"start_col": 0,
"start_line": 266
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2)
val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2
let create n1 n2 = LSeq.create (n1 * n2) (u16 0)
val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem
let mget #n1 #n2 a i j =
index_lt n1 n2 i j;
a.[i * n2 + j]
unfold
let op_Array_Access #n1 #n2 (m:matrix n1 n2) (i,j) = mget m i j
val mset:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> v:elem
-> Pure (matrix n1 n2)
(requires True)
(ensures fun r ->
r.(i,j) == v /\ (forall i' j'. (i', j') <> (i, j) ==> r.(i', j') == a.(i',j')))
let mset #n1 #n2 a i j v =
Classical.forall_intro_2 (index_neq #n1 #n2 i j);
index_lt n1 n2 i j;
a.[i * n2 + j] <- v
unfold
let op_Array_Assignment #n1 #n2 (m:matrix n1 n2) (i,j) x = mset m i j x
val extensionality:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> Lemma
(requires forall i j. a.(i,j) == b.(i,j))
(ensures a == b)
let extensionality #n1 #n2 a b =
let aux (k:size_nat{k < n1 * n2}) : Lemma (index a k == index b k) =
let i = k / n2 in
let j = k % n2 in
div_mul_lt n2 k n1;
assert (i < n1 /\ j < n2);
index_lt n1 n2 i j;
assert (a.(i, j) == a.[i * n2 + j] /\ b.(i, j) == b.[i * n2 + j]);
assert (a.[k] == b.[k]) in
Classical.forall_intro aux;
eq_intro a b;
eq_elim a b
(*
/// Example (of course it doesn't work with Lib.IntTypes)
/// [ 0 2 ]
/// [ 1 3 ]
let m:matrix 2 2 =
assert_norm (List.length [0us; 2us; 1us; 3us] == 4);
Seq.seq_of_list [0us; 2us; 1us; 3us]
let _ = assert_norm (m.(0,0) == 0us /\ m.(1,0) == 1us /\ m.(0,1) == 2us /\ m.(1,1) == 3us)
let _ = assert_norm (let m' = m.(0,0) <- 4us in m'.(0,0) == 4us)
*)
val map:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> f:(elem -> elem)
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == f a.(i,j) }
let map #n1 #n2 f a =
let c = create n1 n2 in
Loops.repeati_inductive n1
(fun i c -> forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c.(i0,j) == f a.(i0,j))
(fun i c ->
Loops.repeati_inductive n2
(fun j c0 ->
(forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c0.(i0,j) == c.(i0,j)) /\
(forall (j0:size_nat{j0 < j}). c0.(i,j0) == f a.(i,j0)))
(fun j c' -> c'.(i,j) <- f a.(i,j))
c)
c
val mod_pow2_felem: logq:size_pos{logq < 16} -> a:elem
-> Pure elem
(requires true)
(ensures fun r -> v r == v a % pow2 logq)
let mod_pow2_felem logq a =
Math.Lemmas.pow2_lt_compat 16 logq;
mod_mask_lemma #U16 a (size logq);
assert (v (mod_mask #U16 #SEC (size logq)) == v ((u16 1 <<. size logq) -. u16 1));
a &. ((u16 1 <<. size logq) -. u16 1)
val mod_pow2:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> logq:size_pos{logq <= 16}
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. v c.(i,j) == v a.(i,j) % pow2 logq }
let mod_pow2 #n1 #n2 logq a =
if logq < 16 then
map (mod_pow2_felem logq) a
else a
val map2:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> f:(elem -> elem -> elem)
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == f a.(i,j) b.(i,j) }
let map2 #n1 #n2 f a b =
let c = create n1 n2 in
Loops.repeati_inductive n1
(fun i c -> forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c.(i0,j) == f a.(i0,j) b.(i0,j))
(fun i c ->
Loops.repeati_inductive n2
(fun j c0 ->
(forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c0.(i0,j) == c.(i0,j)) /\
(forall (j0:size_nat{j0 < j}). c0.(i,j0) == f a.(i,j0) b.(i,j0)))
(fun j c' -> c'.(i,j) <- f a.(i,j) b.(i,j))
c)
c
val add:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == a.(i,j) +. b.(i,j) }
let add #n1 #n2 a b =
map2 add_mod a b
val sub:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == a.(i,j) -. b.(i,j) }
let sub #n1 #n2 a b =
map2 sub_mod a b
val sum_:
#n:size_nat
-> f:(j:size_nat{j < n} -> GTot uint16)
-> i:size_nat{i <= n}
-> GTot uint16
(decreases i)
let rec sum_ #n f i =
if i = 0 then u16 0
else sum_ #n f (i - 1) +. f (i - 1) | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | f: (j: Lib.IntTypes.size_nat{j < n} -> Prims.GTot Lib.IntTypes.uint16)
-> Prims.GTot Lib.IntTypes.uint16 | Prims.GTot | [
"sometrivial"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThan",
"Lib.IntTypes.uint16",
"Spec.Matrix.sum_"
] | [] | false | false | false | false | false | let sum #n f =
| sum_ #n f n | false |
|
Spec.Matrix.fst | Spec.Matrix.extensionality | val extensionality:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> Lemma
(requires forall i j. a.(i,j) == b.(i,j))
(ensures a == b) | val extensionality:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> Lemma
(requires forall i j. a.(i,j) == b.(i,j))
(ensures a == b) | let extensionality #n1 #n2 a b =
let aux (k:size_nat{k < n1 * n2}) : Lemma (index a k == index b k) =
let i = k / n2 in
let j = k % n2 in
div_mul_lt n2 k n1;
assert (i < n1 /\ j < n2);
index_lt n1 n2 i j;
assert (a.(i, j) == a.[i * n2 + j] /\ b.(i, j) == b.[i * n2 + j]);
assert (a.[k] == b.[k]) in
Classical.forall_intro aux;
eq_intro a b;
eq_elim a b | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 13,
"end_line": 149,
"start_col": 0,
"start_line": 137
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2)
val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2
let create n1 n2 = LSeq.create (n1 * n2) (u16 0)
val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem
let mget #n1 #n2 a i j =
index_lt n1 n2 i j;
a.[i * n2 + j]
unfold
let op_Array_Access #n1 #n2 (m:matrix n1 n2) (i,j) = mget m i j
val mset:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> v:elem
-> Pure (matrix n1 n2)
(requires True)
(ensures fun r ->
r.(i,j) == v /\ (forall i' j'. (i', j') <> (i, j) ==> r.(i', j') == a.(i',j')))
let mset #n1 #n2 a i j v =
Classical.forall_intro_2 (index_neq #n1 #n2 i j);
index_lt n1 n2 i j;
a.[i * n2 + j] <- v
unfold
let op_Array_Assignment #n1 #n2 (m:matrix n1 n2) (i,j) x = mset m i j x
val extensionality:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> Lemma
(requires forall i j. a.(i,j) == b.(i,j))
(ensures a == b) | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | a: Spec.Matrix.matrix n1 n2 -> b: Spec.Matrix.matrix n1 n2
-> FStar.Pervasives.Lemma
(requires
forall (i: Lib.IntTypes.size_nat{i < n1 /\ i < n1})
(j: Lib.IntTypes.size_nat{j < n2 /\ j < n2}).
a.(i, j) == b.(i, j)) (ensures a == b) | FStar.Pervasives.Lemma | [
"lemma"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Spec.Matrix.matrix",
"Lib.Sequence.eq_elim",
"Spec.Matrix.elem",
"Prims.unit",
"Lib.Sequence.eq_intro",
"FStar.Classical.forall_intro",
"Prims.op_LessThan",
"Prims.eq2",
"Prims.l_or",
"FStar.Seq.Base.index",
"Lib.Sequence.to_seq",
"Lib.Sequence.index",
"Prims.nat",
"Prims.op_Subtraction",
"Prims.pow2",
"Prims.op_Multiply",
"Prims.l_True",
"Prims.squash",
"Lib.IntTypes.int_t",
"Lib.IntTypes.U16",
"Lib.IntTypes.SEC",
"Prims.Nil",
"FStar.Pervasives.pattern",
"Prims._assert",
"Lib.Sequence.op_String_Access",
"Prims.l_and",
"Spec.Matrix.op_Array_Access",
"FStar.Pervasives.Native.Mktuple2",
"Prims.op_Addition",
"Spec.Matrix.index_lt",
"Lib.Sequence.div_mul_lt",
"Prims.int",
"Prims.op_Modulus",
"Prims.op_Division"
] | [] | false | false | true | false | false | let extensionality #n1 #n2 a b =
| let aux (k: size_nat{k < n1 * n2}) : Lemma (index a k == index b k) =
let i = k / n2 in
let j = k % n2 in
div_mul_lt n2 k n1;
assert (i < n1 /\ j < n2);
index_lt n1 n2 i j;
assert (a.(i, j) == a.[ i * n2 + j ] /\ b.(i, j) == b.[ i * n2 + j ]);
assert (a.[ k ] == b.[ k ])
in
Classical.forall_intro aux;
eq_intro a b;
eq_elim a b | false |
Spec.Matrix.fst | Spec.Matrix.mod_pow2 | val mod_pow2:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> logq:size_pos{logq <= 16}
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. v c.(i,j) == v a.(i,j) % pow2 logq } | val mod_pow2:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> logq:size_pos{logq <= 16}
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. v c.(i,j) == v a.(i,j) % pow2 logq } | let mod_pow2 #n1 #n2 logq a =
if logq < 16 then
map (mod_pow2_felem logq) a
else a | {
"file_name": "specs/frodo/Spec.Matrix.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 8,
"end_line": 208,
"start_col": 0,
"start_line": 205
} | module Spec.Matrix
open FStar.Mul
open Lib.IntTypes
open Lib.Sequence
open Lib.ByteSequence
module LSeq = Lib.Sequence
module Lemmas = Spec.Frodo.Lemmas
module Loops = Lib.LoopCombinators
#set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
/// Auxiliary lemmas
val index_lt:
n1:size_nat
-> n2:size_nat
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> Lemma (i * n2 + j < n1 * n2)
let index_lt n1 n2 i j =
calc (<=) {
i * n2 + j;
(<=) { Math.Lemmas.lemma_mult_le_right n2 i (n1 - 1) }
(n1 - 1) * n2 + j;
(==) { Math.Lemmas.distributivity_sub_left n1 1 n2 }
n1 * n2 - n2 + j;
(<=) { }
n1 * n2 - 1;
}
private
val index_neq:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> i:size_nat{i < n1}
-> j:nat{j < n2}
-> i':nat{i' < n1}
-> j':nat{j' < n2}
-> Lemma (((i', j') <> (i, j) ==> (i' * n2 + j' <> i * n2 + j) /\ i' * n2 + j' < n1 * n2))
let index_neq #n1 #n2 i j i' j' =
index_lt n1 n2 i' j';
assert (i' * n2 + j' < n1 * n2);
if i' < i then
calc (<) {
i' * n2 + j';
(<) { }
i' * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i' 1 n2 }
(i' + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i' + 1) i }
i * n2;
(<=) { }
i * n2 + j;
}
else if i = i' then ()
else
calc (<) {
i * n2 + j;
(<) { }
i * n2 + n2;
(==) { Math.Lemmas.distributivity_add_left i 1 n2 }
(i + 1) * n2;
(<=) { Math.Lemmas.lemma_mult_le_right n2 (i + 1) i' }
i' * n2;
(<=) { }
i' * n2 + j';
}
/// Matrices as flat sequences
unfold
let elem = uint16
unfold
let matrix (n1:size_nat) (n2:size_nat{n1 * n2 <= max_size_t}) = LSeq.lseq elem (n1 * n2)
val create: n1:size_nat -> n2:size_nat{n1 * n2 <= max_size_t} -> matrix n1 n2
let create n1 n2 = LSeq.create (n1 * n2) (u16 0)
val mget:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> elem
let mget #n1 #n2 a i j =
index_lt n1 n2 i j;
a.[i * n2 + j]
unfold
let op_Array_Access #n1 #n2 (m:matrix n1 n2) (i,j) = mget m i j
val mset:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> i:size_nat{i < n1}
-> j:size_nat{j < n2}
-> v:elem
-> Pure (matrix n1 n2)
(requires True)
(ensures fun r ->
r.(i,j) == v /\ (forall i' j'. (i', j') <> (i, j) ==> r.(i', j') == a.(i',j')))
let mset #n1 #n2 a i j v =
Classical.forall_intro_2 (index_neq #n1 #n2 i j);
index_lt n1 n2 i j;
a.[i * n2 + j] <- v
unfold
let op_Array_Assignment #n1 #n2 (m:matrix n1 n2) (i,j) x = mset m i j x
val extensionality:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> a:matrix n1 n2
-> b:matrix n1 n2
-> Lemma
(requires forall i j. a.(i,j) == b.(i,j))
(ensures a == b)
let extensionality #n1 #n2 a b =
let aux (k:size_nat{k < n1 * n2}) : Lemma (index a k == index b k) =
let i = k / n2 in
let j = k % n2 in
div_mul_lt n2 k n1;
assert (i < n1 /\ j < n2);
index_lt n1 n2 i j;
assert (a.(i, j) == a.[i * n2 + j] /\ b.(i, j) == b.[i * n2 + j]);
assert (a.[k] == b.[k]) in
Classical.forall_intro aux;
eq_intro a b;
eq_elim a b
(*
/// Example (of course it doesn't work with Lib.IntTypes)
/// [ 0 2 ]
/// [ 1 3 ]
let m:matrix 2 2 =
assert_norm (List.length [0us; 2us; 1us; 3us] == 4);
Seq.seq_of_list [0us; 2us; 1us; 3us]
let _ = assert_norm (m.(0,0) == 0us /\ m.(1,0) == 1us /\ m.(0,1) == 2us /\ m.(1,1) == 3us)
let _ = assert_norm (let m' = m.(0,0) <- 4us in m'.(0,0) == 4us)
*)
val map:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> f:(elem -> elem)
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. c.(i,j) == f a.(i,j) }
let map #n1 #n2 f a =
let c = create n1 n2 in
Loops.repeati_inductive n1
(fun i c -> forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c.(i0,j) == f a.(i0,j))
(fun i c ->
Loops.repeati_inductive n2
(fun j c0 ->
(forall (i0:size_nat{i0 < i}) (j:size_nat{j < n2}). c0.(i0,j) == c.(i0,j)) /\
(forall (j0:size_nat{j0 < j}). c0.(i,j0) == f a.(i,j0)))
(fun j c' -> c'.(i,j) <- f a.(i,j))
c)
c
val mod_pow2_felem: logq:size_pos{logq < 16} -> a:elem
-> Pure elem
(requires true)
(ensures fun r -> v r == v a % pow2 logq)
let mod_pow2_felem logq a =
Math.Lemmas.pow2_lt_compat 16 logq;
mod_mask_lemma #U16 a (size logq);
assert (v (mod_mask #U16 #SEC (size logq)) == v ((u16 1 <<. size logq) -. u16 1));
a &. ((u16 1 <<. size logq) -. u16 1)
val mod_pow2:
#n1:size_nat
-> #n2:size_nat{n1 * n2 <= max_size_t}
-> logq:size_pos{logq <= 16}
-> a:matrix n1 n2
-> c:matrix n1 n2{ forall i j. v c.(i,j) == v a.(i,j) % pow2 logq } | {
"checked_file": "/",
"dependencies": [
"Spec.Frodo.Lemmas.fst.checked",
"prims.fst.checked",
"Lib.Sequence.fsti.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.ByteSequence.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Classical.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": false,
"source_file": "Spec.Matrix.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.LoopCombinators",
"short_module": "Loops"
},
{
"abbrev": true,
"full_module": "Spec.Frodo.Lemmas",
"short_module": "Lemmas"
},
{
"abbrev": true,
"full_module": "Lib.Sequence",
"short_module": "LSeq"
},
{
"abbrev": false,
"full_module": "Lib.ByteSequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Sequence",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | logq: Lib.IntTypes.size_pos{logq <= 16} -> a: Spec.Matrix.matrix n1 n2
-> c:
Spec.Matrix.matrix n1 n2
{ forall (i: Lib.IntTypes.size_nat{i < n1 /\ i < n1})
(j: Lib.IntTypes.size_nat{j < n2 /\ j < n2}).
Lib.IntTypes.v c.(i, j) == Lib.IntTypes.v a.(i, j) % Prims.pow2 logq } | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Lib.IntTypes.max_size_t",
"Lib.IntTypes.size_pos",
"Spec.Matrix.matrix",
"Prims.op_LessThan",
"Spec.Matrix.map",
"Spec.Matrix.mod_pow2_felem",
"Prims.bool",
"Prims.l_Forall",
"Prims.l_and",
"Prims.eq2",
"Prims.int",
"Lib.IntTypes.v",
"Lib.IntTypes.U16",
"Lib.IntTypes.SEC",
"Spec.Matrix.op_Array_Access",
"FStar.Pervasives.Native.Mktuple2",
"Prims.op_Modulus",
"Prims.pow2"
] | [] | false | false | false | false | false | let mod_pow2 #n1 #n2 logq a =
| if logq < 16 then map (mod_pow2_felem logq) a else a | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.