From 5972da6ecc04ab45a2bbcf0d1425226bc9138ad8 Mon Sep 17 00:00:00 2001 From: Kacper Marzecki Date: Sun, 29 Jun 2025 20:26:26 +0200 Subject: [PATCH] checkpoint idk --- new.exs | 999 +++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 695 insertions(+), 304 deletions(-) diff --git a/new.exs b/new.exs index 7c42fa0..824abdd 100644 --- a/new.exs +++ b/new.exs @@ -1,6 +1,5 @@ Code.require_file("./debug.exs") - defmodule Tdd.TypeSpec do @moduledoc """ Defines the `TypeSpec` structure and functions for its manipulation. @@ -37,9 +36,10 @@ defmodule Tdd.TypeSpec do @spec normalize(t()) :: t() def normalize(spec) do {intermediate_normalized, _counter_after_pass1} = normalize_pass1(spec, %{}, 0) + {final_spec_before_subtype_redux, _mu_counter, _lambda_counter} = canonical_rename_pass(intermediate_normalized, %{}, 0, 0) - + apply_subtype_reduction(final_spec_before_subtype_redux) end @@ -67,7 +67,8 @@ defmodule Tdd.TypeSpec do final_members = Enum.reject(unique_no_none, fn member_to_check -> Enum.any?(unique_no_none, fn other_member -> - member_to_check != other_member and is_subtype?(member_to_check, other_member, true) + member_to_check != other_member and + is_subtype?(member_to_check, other_member, true) end) end) @@ -85,7 +86,8 @@ defmodule Tdd.TypeSpec do Enum.flat_map(recursively_reduced_members, fn {:intersect, sub_members} -> sub_members # get_supertypes expects normalized spec, and its output is also normalized - m -> get_supertypes(m, true) # Pass flag + # Pass flag + m -> get_supertypes(m, true) end) unique_no_any = @@ -100,7 +102,8 @@ defmodule Tdd.TypeSpec do final_members = Enum.reject(unique_no_any, fn member_to_check -> Enum.any?(unique_no_any, fn other_member -> - member_to_check != other_member and is_subtype?(other_member, member_to_check, true) + member_to_check != other_member and + is_subtype?(other_member, member_to_check, true) end) end) @@ -111,98 +114,150 @@ defmodule Tdd.TypeSpec do end end - {:negation, body} -> {:negation, apply_subtype_reduction(body)} - {:tuple, elements} -> {:tuple, Enum.map(elements, &apply_subtype_reduction/1)} - {:cons, head, tail} -> {:cons, apply_subtype_reduction(head), apply_subtype_reduction(tail)} - {:mu, var_name, body} -> {:mu, var_name, apply_subtype_reduction(body)} - {:type_lambda, params, body} -> {:type_lambda, params, apply_subtype_reduction(body)} + {:negation, body} -> + {:negation, apply_subtype_reduction(body)} + + {:tuple, elements} -> + {:tuple, Enum.map(elements, &apply_subtype_reduction/1)} + + {:cons, head, tail} -> + {:cons, apply_subtype_reduction(head), apply_subtype_reduction(tail)} + + {:mu, var_name, body} -> + {:mu, var_name, apply_subtype_reduction(body)} + + {:type_lambda, params, body} -> + {:type_lambda, params, apply_subtype_reduction(body)} + {:type_apply, constructor, args} -> - {:type_apply, apply_subtype_reduction(constructor), Enum.map(args, &apply_subtype_reduction/1)} - atomic_or_literal -> atomic_or_literal + {:type_apply, apply_subtype_reduction(constructor), + Enum.map(args, &apply_subtype_reduction/1)} + + atomic_or_literal -> + atomic_or_literal end end + # ------------------------------------------------------------------ # Pass 1: Structural Normalization, Beta-Reduction, Initial Alpha-Conversion # Returns: {normalized_spec, next_counter} # ------------------------------------------------------------------ defp normalize_pass1(spec, env, counter) do - res_tuple = case spec do - s when is_atom(s) and s in [:any, :none, :atom, :integer, :list, :tuple] -> {s, counter} - {:literal, _val} = lit_spec -> {lit_spec, counter} - {:type_var, name} -> {Map.get(env, name, spec), counter} + res_tuple = + case spec do + s when is_atom(s) and s in [:any, :none, :atom, :integer, :list, :tuple] -> + {s, counter} - {:negation, sub_spec} -> normalize_negation_pass1(sub_spec, env, counter) + {:literal, _val} = lit_spec -> + {lit_spec, counter} - {:tuple, elements} -> - {normalized_elements, next_counter_after_elements} = - map_fold_counter_for_pass1(elements, env, counter, &normalize_pass1/3) - {{:tuple, normalized_elements}, next_counter_after_elements} + {:type_var, name} -> + {Map.get(env, name, spec), counter} - {:cons, head, tail} -> - {normalized_head, counter_after_head} = normalize_pass1(head, env, counter) - {normalized_tail, counter_after_tail} = normalize_pass1(tail, env, counter_after_head) - {{:cons, normalized_head, normalized_tail}, counter_after_tail} + {:negation, sub_spec} -> + normalize_negation_pass1(sub_spec, env, counter) - {:integer_range, min, max} -> - range_spec = - if is_integer(min) and is_integer(max) and min > max do - :none - else - {:integer_range, min, max} - end - {range_spec, counter} + {:tuple, elements} -> + {normalized_elements, next_counter_after_elements} = + map_fold_counter_for_pass1(elements, env, counter, &normalize_pass1/3) - {:union, members} -> normalize_union_pass1(members, env, counter) - {:intersect, members} -> normalize_intersection_pass1(members, env, counter) + {{:tuple, normalized_elements}, next_counter_after_elements} - {:list_of, element_spec} -> - {normalized_element, counter_after_element} = normalize_pass1(element_spec, env, counter) - internal_rec_var_name = :"$ListOfInternalRecVar_Pass1$" - list_body = - {:union, - [ - {:literal, []}, - {:cons, normalized_element, {:type_var, internal_rec_var_name}} - ]} - normalize_pass1({:mu, internal_rec_var_name, list_body}, env, counter_after_element) + {:cons, head, tail} -> + {normalized_head, counter_after_head} = normalize_pass1(head, env, counter) + {normalized_tail, counter_after_tail} = normalize_pass1(tail, env, counter_after_head) + {{:cons, normalized_head, normalized_tail}, counter_after_tail} - - {:mu, var_name, body} -> - fresh_temp_name = fresh_var_name(:p1_m_var, counter) - body_env = Map.put(env, var_name, {:type_var, fresh_temp_name}) - {normalized_body, next_counter_after_body} = normalize_pass1(body, body_env, counter + 1) - {{:mu, fresh_temp_name, normalized_body}, next_counter_after_body} - - {:type_lambda, param_names, body} -> - {reversed_fresh_temp_names, next_counter_after_params, body_env} = - Enum.reduce(param_names, {[], counter, env}, fn param_name, {acc_fresh_names, cnt, current_env} -> - fresh_name = fresh_var_name(:p1_lambda_var, cnt) - {[fresh_name | acc_fresh_names], cnt + 1, Map.put(current_env, param_name, {:type_var, fresh_name})} - end) - fresh_temp_param_names = Enum.reverse(reversed_fresh_temp_names) - {normalized_body, final_counter} = normalize_pass1(body, body_env, next_counter_after_params) - {{:type_lambda, fresh_temp_param_names, normalized_body}, final_counter} - - {:type_apply, constructor_spec, arg_specs} -> - {normalized_constructor, counter_after_constructor} = normalize_pass1(constructor_spec, env, counter) - {normalized_arg_specs, counter_after_args} = - map_fold_counter_for_pass1(arg_specs, env, counter_after_constructor, &normalize_pass1/3) - - case normalized_constructor do - {:type_lambda, pass1_formal_params, pass1_lambda_body} -> - if length(pass1_formal_params) != length(normalized_arg_specs) do - raise "TypeSpec.normalize_pass1: Arity mismatch in application. Expected #{length(pass1_formal_params)} args, got #{length(normalized_arg_specs)}. Lambda: #{inspect(normalized_constructor)}, Args: #{inspect(normalized_arg_specs)}" + {:integer_range, min, max} -> + range_spec = + if is_integer(min) and is_integer(max) and min > max do + :none else - substitution_map = Map.new(Enum.zip(pass1_formal_params, normalized_arg_specs)) - substituted_body = substitute_vars_pass1(pass1_lambda_body, substitution_map, MapSet.new()) - normalize_pass1(substituted_body, env, counter_after_args) + {:integer_range, min, max} end - _other_constructor -> - {{:type_apply, normalized_constructor, normalized_arg_specs}, counter_after_args} - end - other_spec -> + + {range_spec, counter} + + {:union, members} -> + normalize_union_pass1(members, env, counter) + + {:intersect, members} -> + normalize_intersection_pass1(members, env, counter) + + {:list_of, element_spec} -> + {normalized_element, counter_after_element} = + normalize_pass1(element_spec, env, counter) + + internal_rec_var_name = :"$ListOfInternalRecVar_Pass1$" + + list_body = + {:union, + [ + {:literal, []}, + {:cons, normalized_element, {:type_var, internal_rec_var_name}} + ]} + + normalize_pass1({:mu, internal_rec_var_name, list_body}, env, counter_after_element) + + {:mu, var_name, body} -> + fresh_temp_name = fresh_var_name(:p1_m_var, counter) + body_env = Map.put(env, var_name, {:type_var, fresh_temp_name}) + + {normalized_body, next_counter_after_body} = + normalize_pass1(body, body_env, counter + 1) + + {{:mu, fresh_temp_name, normalized_body}, next_counter_after_body} + + {:type_lambda, param_names, body} -> + {reversed_fresh_temp_names, next_counter_after_params, body_env} = + Enum.reduce(param_names, {[], counter, env}, fn param_name, + {acc_fresh_names, cnt, current_env} -> + fresh_name = fresh_var_name(:p1_lambda_var, cnt) + + {[fresh_name | acc_fresh_names], cnt + 1, + Map.put(current_env, param_name, {:type_var, fresh_name})} + end) + + fresh_temp_param_names = Enum.reverse(reversed_fresh_temp_names) + + {normalized_body, final_counter} = + normalize_pass1(body, body_env, next_counter_after_params) + + {{:type_lambda, fresh_temp_param_names, normalized_body}, final_counter} + + {:type_apply, constructor_spec, arg_specs} -> + {normalized_constructor, counter_after_constructor} = + normalize_pass1(constructor_spec, env, counter) + + {normalized_arg_specs, counter_after_args} = + map_fold_counter_for_pass1( + arg_specs, + env, + counter_after_constructor, + &normalize_pass1/3 + ) + + case normalized_constructor do + {:type_lambda, pass1_formal_params, pass1_lambda_body} -> + if length(pass1_formal_params) != length(normalized_arg_specs) do + raise "TypeSpec.normalize_pass1: Arity mismatch in application. Expected #{length(pass1_formal_params)} args, got #{length(normalized_arg_specs)}. Lambda: #{inspect(normalized_constructor)}, Args: #{inspect(normalized_arg_specs)}" + else + substitution_map = Map.new(Enum.zip(pass1_formal_params, normalized_arg_specs)) + + substituted_body = + substitute_vars_pass1(pass1_lambda_body, substitution_map, MapSet.new()) + + normalize_pass1(substituted_body, env, counter_after_args) + end + + _other_constructor -> + {{:type_apply, normalized_constructor, normalized_arg_specs}, counter_after_args} + end + + other_spec -> raise "TypeSpec.normalize_pass1: Unhandled spec form: #{inspect(other_spec)}" - end + end + res_tuple end @@ -220,30 +275,51 @@ defmodule Tdd.TypeSpec do else Map.get(substitutions, name, spec) end - {:mu, var_name, body} -> + + {:mu, var_name, body} -> newly_bound_scope = MapSet.put(bound_in_scope, var_name) active_substitutions = Map.delete(substitutions, var_name) {:mu, var_name, substitute_vars_pass1(body, active_substitutions, newly_bound_scope)} - {:type_lambda, param_names, body} -> + + {:type_lambda, param_names, body} -> newly_bound_scope = Enum.reduce(param_names, bound_in_scope, &MapSet.put(&2, &1)) active_substitutions = Enum.reduce(param_names, substitutions, &Map.delete(&2, &1)) - {:type_lambda, param_names, substitute_vars_pass1(body, active_substitutions, newly_bound_scope)} - {:negation, sub} -> {:negation, substitute_vars_pass1(sub, substitutions, bound_in_scope)} - {:tuple, elements} -> {:tuple, Enum.map(elements, &substitute_vars_pass1(&1, substitutions, bound_in_scope))} - {:cons, h, t} -> {:cons, substitute_vars_pass1(h, substitutions, bound_in_scope), substitute_vars_pass1(t, substitutions, bound_in_scope)} - {:list_of, e} -> {:list_of, substitute_vars_pass1(e, substitutions, bound_in_scope)} - {:union, members} -> {:union, Enum.map(members, &substitute_vars_pass1(&1, substitutions, bound_in_scope))} - {:intersect, members} -> {:intersect, Enum.map(members, &substitute_vars_pass1(&1, substitutions, bound_in_scope))} + + {:type_lambda, param_names, + substitute_vars_pass1(body, active_substitutions, newly_bound_scope)} + + {:negation, sub} -> + {:negation, substitute_vars_pass1(sub, substitutions, bound_in_scope)} + + {:tuple, elements} -> + {:tuple, Enum.map(elements, &substitute_vars_pass1(&1, substitutions, bound_in_scope))} + + {:cons, h, t} -> + {:cons, substitute_vars_pass1(h, substitutions, bound_in_scope), + substitute_vars_pass1(t, substitutions, bound_in_scope)} + + {:list_of, e} -> + {:list_of, substitute_vars_pass1(e, substitutions, bound_in_scope)} + + {:union, members} -> + {:union, Enum.map(members, &substitute_vars_pass1(&1, substitutions, bound_in_scope))} + + {:intersect, members} -> + {:intersect, Enum.map(members, &substitute_vars_pass1(&1, substitutions, bound_in_scope))} + {:type_apply, con, args} -> new_con = substitute_vars_pass1(con, substitutions, bound_in_scope) new_args = Enum.map(args, &substitute_vars_pass1(&1, substitutions, bound_in_scope)) {:type_apply, new_con, new_args} - _atomic_or_simple_spec -> spec + + _atomic_or_simple_spec -> + spec end end defp normalize_negation_pass1(sub_spec, env, counter) do {normalized_sub, next_counter} = normalize_pass1(sub_spec, env, counter) + res_spec = case normalized_sub do {:negation, inner_spec} -> inner_spec @@ -251,6 +327,7 @@ defmodule Tdd.TypeSpec do :none -> :any _ -> {:negation, normalized_sub} end + {res_spec, next_counter} end @@ -265,6 +342,7 @@ defmodule Tdd.TypeSpec do {:union, sub_members} -> sub_members _ -> [normalized_member_spec_term] end + {members_to_add_to_overall_list, counter_after_this_member_normalized} end) @@ -274,17 +352,19 @@ defmodule Tdd.TypeSpec do normalized_and_flattened |> Enum.reject(&(&1 == :none)) |> Enum.uniq() - + if Enum.member?(unique_members, :any) do {:any, final_counter_after_all_members} else sorted_for_pass1 = Enum.sort(unique_members) + resulting_spec = case sorted_for_pass1 do [] -> :none [single_member] -> single_member list_members -> {:union, list_members} end + {resulting_spec, final_counter_after_all_members} end end @@ -300,6 +380,7 @@ defmodule Tdd.TypeSpec do {:intersect, sub_members} -> sub_members _ -> get_supertypes_pass1(normalized_member_spec_term) end + {expanded_members, counter_after_this_member_normalized} end) @@ -314,12 +395,14 @@ defmodule Tdd.TypeSpec do {:none, final_counter_after_all_members} else sorted_for_pass1 = Enum.sort(unique_members) + resulting_spec = case sorted_for_pass1 do [] -> :any [single_member] -> single_member list_members -> {:intersect, list_members} end + {resulting_spec, final_counter_after_all_members} end end @@ -331,11 +414,12 @@ defmodule Tdd.TypeSpec do {:literal, val} when is_integer(val) -> [:integer] {:literal, val} when is_list(val) -> [:list] {:literal, val} when is_tuple(val) -> [:tuple] - {:mu, _v, _body} -> [] + {:mu, _v, _body} -> [] {:tuple, _} -> [:tuple] {:integer_range, _, _} -> [:integer] _ -> [] end + MapSet.to_list(MapSet.new([spec | supertypes])) end @@ -344,19 +428,28 @@ defmodule Tdd.TypeSpec do {:mu, old_var_name, body} -> new_canonical_name = fresh_var_name(:m_var, mu_c) body_env = Map.put(env, old_var_name, {:type_var, new_canonical_name}) + {renamed_body, next_mu_c, next_lambda_c} = canonical_rename_pass(body, body_env, mu_c + 1, lambda_c) + {{:mu, new_canonical_name, renamed_body}, next_mu_c, next_lambda_c} {:type_lambda, old_param_names, body} -> {reversed_new_param_names, next_lambda_c_after_params, body_env} = - Enum.reduce(old_param_names, {[], lambda_c, env}, fn old_name, {acc_new_names, current_lc, current_env} -> + Enum.reduce(old_param_names, {[], lambda_c, env}, fn old_name, + {acc_new_names, current_lc, + current_env} -> fresh_canonical_name = fresh_var_name(:lambda_var, current_lc) - {[fresh_canonical_name | acc_new_names], current_lc + 1, Map.put(current_env, old_name, {:type_var, fresh_canonical_name})} + + {[fresh_canonical_name | acc_new_names], current_lc + 1, + Map.put(current_env, old_name, {:type_var, fresh_canonical_name})} end) + new_canonical_param_names = Enum.reverse(reversed_new_param_names) + {renamed_body, final_mu_c, final_lambda_c} = canonical_rename_pass(body, body_env, mu_c, next_lambda_c_after_params) + {{:type_lambda, new_canonical_param_names, renamed_body}, final_mu_c, final_lambda_c} {:type_var, name} -> @@ -369,35 +462,70 @@ defmodule Tdd.TypeSpec do {:tuple, elements} -> {renamed_elements, next_mu_c, next_lambda_c} = map_foldl_counters_for_rename(elements, env, mu_c, lambda_c, &canonical_rename_pass/4) + {{:tuple, renamed_elements}, next_mu_c, next_lambda_c} {:cons, head, tail} -> - {renamed_head, mu_c_after_head, lambda_c_after_head} = canonical_rename_pass(head, env, mu_c, lambda_c) - {renamed_tail, mu_c_after_tail, lambda_c_after_tail} = canonical_rename_pass(tail, env, mu_c_after_head, lambda_c_after_head) + {renamed_head, mu_c_after_head, lambda_c_after_head} = + canonical_rename_pass(head, env, mu_c, lambda_c) + + {renamed_tail, mu_c_after_tail, lambda_c_after_tail} = + canonical_rename_pass(tail, env, mu_c_after_head, lambda_c_after_head) + {{:cons, renamed_head, renamed_tail}, mu_c_after_tail, lambda_c_after_tail} {:union, members} -> - sorted_members = Enum.sort(members) + sorted_members = Enum.sort(members) + {renamed_members, next_mu_c, next_lambda_c} = - map_foldl_counters_for_rename(sorted_members, env, mu_c, lambda_c, &canonical_rename_pass/4) - {{:union, Enum.sort(renamed_members)}, next_mu_c, next_lambda_c} + map_foldl_counters_for_rename( + sorted_members, + env, + mu_c, + lambda_c, + &canonical_rename_pass/4 + ) + + {{:union, Enum.sort(renamed_members)}, next_mu_c, next_lambda_c} {:intersect, members} -> sorted_members = Enum.sort(members) + {renamed_members, next_mu_c, next_lambda_c} = - map_foldl_counters_for_rename(sorted_members, env, mu_c, lambda_c, &canonical_rename_pass/4) - {{:intersect, Enum.sort(renamed_members)}, next_mu_c, next_lambda_c} + map_foldl_counters_for_rename( + sorted_members, + env, + mu_c, + lambda_c, + &canonical_rename_pass/4 + ) + + {{:intersect, Enum.sort(renamed_members)}, next_mu_c, next_lambda_c} {:type_apply, constructor_spec, arg_specs} -> {renamed_constructor, mu_c_after_con, lambda_c_after_con} = canonical_rename_pass(constructor_spec, env, mu_c, lambda_c) + {renamed_args, mu_c_after_args, lambda_c_after_args} = - map_foldl_counters_for_rename(arg_specs, env, mu_c_after_con, lambda_c_after_con, &canonical_rename_pass/4) + map_foldl_counters_for_rename( + arg_specs, + env, + mu_c_after_con, + lambda_c_after_con, + &canonical_rename_pass/4 + ) + {{:type_apply, renamed_constructor, renamed_args}, mu_c_after_args, lambda_c_after_args} - s when is_atom(s) -> {s, mu_c, lambda_c} - {:literal, _} = spec -> {spec, mu_c, lambda_c} - {:integer_range, _, _} = spec -> {spec, mu_c, lambda_c} + s when is_atom(s) -> + {s, mu_c, lambda_c} + + {:literal, _} = spec -> + {spec, mu_c, lambda_c} + + {:integer_range, _, _} = spec -> + {spec, mu_c, lambda_c} + {:list_of, _} = spec -> raise "TypeSpec.canonical_rename_pass: Unexpected :list_of, should be :mu. Spec: #{inspect(spec)}" @@ -412,6 +540,7 @@ defmodule Tdd.TypeSpec do {processed_item, next_mc, next_lc} = fun.(item, env, mc, lc) {[processed_item | acc_items], next_mc, next_lc} end) + {Enum.reverse(reversed_results), final_mu_c, final_lambda_c} end @@ -427,13 +556,23 @@ defmodule Tdd.TypeSpec do @spec is_subtype?(t(), t(), boolean) :: boolean def is_subtype?(spec1, spec2, already_normalized) do cond do - spec1 == spec2 -> true - spec1 == :none -> true - spec2 == :any -> true - spec1 == :any and spec2 != :any -> false - spec2 == :none and spec1 != :none -> false + spec1 == spec2 -> + true + + spec1 == :none -> + true + + spec2 == :any -> + true + + spec1 == :any and spec2 != :any -> + false + + spec2 == :none and spec1 != :none -> + false + true -> - {norm_s1, norm_s2} = + {norm_s1, norm_s2} = if already_normalized do {spec1, spec2} else @@ -449,109 +588,195 @@ defmodule Tdd.TypeSpec do end defp do_is_subtype_structural?(spec1, spec2, visited) do - if MapSet.member?(visited, {spec1, spec2}) do + if MapSet.member?(visited, {spec1, spec2}) do true else - cond do - spec1 == :none -> true - spec2 == :any -> true - spec1 == :any and spec2 != :any -> false - spec2 == :none and spec1 != :none -> false - spec1 == spec2 -> true + cond do + spec1 == :none -> + true - true -> - new_visited = MapSet.put(visited, {spec1, spec2}) + spec2 == :any -> + true - case {spec1, spec2} do - {{:union, members1}, _} -> Enum.all?(members1, &do_is_subtype_structural?(&1, spec2, new_visited)) - {_, {:union, members2}} -> Enum.any?(members2, &do_is_subtype_structural?(spec1, &1, new_visited)) - {{:intersect, members1}, _} -> Enum.any?(members1, &do_is_subtype_structural?(&1, spec2, new_visited)) - {_, {:intersect, members2}} -> Enum.all?(members2, &do_is_subtype_structural?(spec1, &1, new_visited)) + spec1 == :any and spec2 != :any -> + false - {s1, s2} when is_atom(s1) and is_atom(s2) and not (s1 in [:any, :none]) and not (s2 in [:any, :none]) -> s1 == s2 - {{:literal, v1}, {:literal, v2}} -> v1 == v2 - {{:literal, val}, :atom} when is_atom(val) -> true - {{:literal, val}, :integer} when is_integer(val) -> true - {{:literal, val}, :list} when is_list(val) -> true - {{:literal, val}, :tuple} when is_tuple(val) -> true + spec2 == :none and spec1 != :none -> + false - {{:tuple, elems1}, {:tuple, elems2}} when length(elems1) == length(elems2) -> - Enum.zip_with(elems1, elems2, &do_is_subtype_structural?(&1, &2, new_visited)) |> Enum.all?() - {{:tuple, _}, :tuple} -> true + spec1 == spec2 -> + true - {{:integer_range, _, _}, :integer} -> true - {{:integer_range, min1, max1}, {:integer_range, min2, max2}} -> - min1_gte_min2 = case {min1, min2} do {:neg_inf, _} -> min2 == :neg_inf; {_, :neg_inf} -> true; {m1_v,m2_v} when is_integer(m1_v) and is_integer(m2_v) -> m1_v >= m2_v; _ -> false end - max1_lte_max2 = case {max1, max2} do {:pos_inf, _} -> max2 == :pos_inf; {_, :pos_inf} -> true; {m1_v,m2_v} when is_integer(m1_v) and is_integer(m2_v) -> m1_v <= m2_v; _ -> false end - min1_gte_min2 and max1_lte_max2 - {{:literal, val}, {:integer_range, min, max}} when is_integer(val) -> - (min == :neg_inf or val >= min) and (max == :pos_inf or val <= max) + true -> + new_visited = MapSet.put(visited, {spec1, spec2}) - {{:mu, v1, b1_body}, {:mu, v2, b2_body}} -> - cond do - is_list_mu_form(b1_body, v1) and is_list_mu_form(b2_body, v2) -> - e1 = extract_list_mu_element(b1_body, v1) - e2 = extract_list_mu_element(b2_body, v2) - do_is_subtype_structural?(e1, e2, new_visited) - v1 == v2 -> # Canonical vars are the same, implies types were structurally identical before renaming, or one unfolds to other - subst_map1 = %{v1 => spec1} # spec1 is the mu-type itself (μv1.b1_body) - subst_map2 = %{v2 => spec2} # spec2 is the mu-type itself (μv2.b2_body) - unfolded_b1 = substitute_vars_canonical(b1_body, subst_map1) - unfolded_b2 = substitute_vars_canonical(b2_body, subst_map2) - do_is_subtype_structural?(unfolded_b1, unfolded_b2, new_visited) + case {spec1, spec2} do + {{:union, members1}, _} -> + Enum.all?(members1, &do_is_subtype_structural?(&1, spec2, new_visited)) - true -> # Different canonical mu-variables, not list forms - # This path is taken for Mu_B_final vs Mu_C_final if spec1/spec2 were Mu_B_final/Mu_C_final *before* normalization. - # If they were normalized, they'd be identical if equivalent. - # If is_subtype? is called with already-canonical forms Mu_B_final and Mu_C_final, - # then v1 = :m_var1, v2 = :m_var2. So this `true` branch is taken. - false - end + {_, {:union, members2}} -> + Enum.any?(members2, &do_is_subtype_structural?(spec1, &1, new_visited)) - {{:mu, v_s1, body_s1}, :list} -> is_list_mu_form(body_s1, v_s1) - {{:negation, n_body1}, {:negation, n_body2}} -> - do_is_subtype_structural?(n_body2, n_body1, new_visited) - _ -> false - end - end + {{:intersect, members1}, _} -> + Enum.any?(members1, &do_is_subtype_structural?(&1, spec2, new_visited)) + + {_, {:intersect, members2}} -> + Enum.all?(members2, &do_is_subtype_structural?(spec1, &1, new_visited)) + + {s1, s2} + when is_atom(s1) and is_atom(s2) and s1 not in [:any, :none] and + s2 not in [:any, :none] -> + s1 == s2 + + {{:literal, v1}, {:literal, v2}} -> + v1 == v2 + + {{:literal, val}, :atom} when is_atom(val) -> + true + + {{:literal, val}, :integer} when is_integer(val) -> + true + + {{:literal, val}, :list} when is_list(val) -> + true + + {{:literal, val}, :tuple} when is_tuple(val) -> + true + + {{:tuple, elems1}, {:tuple, elems2}} when length(elems1) == length(elems2) -> + Enum.zip_with(elems1, elems2, &do_is_subtype_structural?(&1, &2, new_visited)) + |> Enum.all?() + + {{:tuple, _}, :tuple} -> + true + + {{:integer_range, _, _}, :integer} -> + true + + {{:integer_range, min1, max1}, {:integer_range, min2, max2}} -> + min1_gte_min2 = + case {min1, min2} do + {:neg_inf, _} -> min2 == :neg_inf + {_, :neg_inf} -> true + {m1_v, m2_v} when is_integer(m1_v) and is_integer(m2_v) -> m1_v >= m2_v + _ -> false + end + + max1_lte_max2 = + case {max1, max2} do + {:pos_inf, _} -> max2 == :pos_inf + {_, :pos_inf} -> true + {m1_v, m2_v} when is_integer(m1_v) and is_integer(m2_v) -> m1_v <= m2_v + _ -> false + end + + min1_gte_min2 and max1_lte_max2 + + {{:literal, val}, {:integer_range, min, max}} when is_integer(val) -> + (min == :neg_inf or val >= min) and (max == :pos_inf or val <= max) + + {{:mu, v1, b1_body}, {:mu, v2, b2_body}} -> + cond do + is_list_mu_form(b1_body, v1) and is_list_mu_form(b2_body, v2) -> + e1 = extract_list_mu_element(b1_body, v1) + e2 = extract_list_mu_element(b2_body, v2) + do_is_subtype_structural?(e1, e2, new_visited) + + # Canonical vars are the same, implies types were structurally identical before renaming, or one unfolds to other + v1 == v2 -> + # spec1 is the mu-type itself (μv1.b1_body) + subst_map1 = %{v1 => spec1} + # spec2 is the mu-type itself (μv2.b2_body) + subst_map2 = %{v2 => spec2} + unfolded_b1 = substitute_vars_canonical(b1_body, subst_map1) + unfolded_b2 = substitute_vars_canonical(b2_body, subst_map2) + do_is_subtype_structural?(unfolded_b1, unfolded_b2, new_visited) + + # Different canonical mu-variables, not list forms + true -> + # This path is taken for Mu_B_final vs Mu_C_final if spec1/spec2 were Mu_B_final/Mu_C_final *before* normalization. + # If they were normalized, they'd be identical if equivalent. + # If is_subtype? is called with already-canonical forms Mu_B_final and Mu_C_final, + # then v1 = :m_var1, v2 = :m_var2. So this `true` branch is taken. + # spec1 is the mu-type itself (μv1.b1_body) + # subst_map1 = %{v1 => spec1} + # # spec2 is the mu-type itself (μv2.b2_body) + # subst_map2 = %{v2 => spec2} + # unfolded_b1 = substitute_vars_canonical(b1_body, subst_map1) + # unfolded_b2 = substitute_vars_canonical(b2_body, subst_map2) + # do_is_subtype_structural?(unfolded_b1, unfolded_b2, new_visited) + false + end + + {{:mu, v_s1, body_s1}, :list} -> + is_list_mu_form(body_s1, v_s1) + + {{:negation, n_body1}, {:negation, n_body2}} -> + do_is_subtype_structural?(n_body2, n_body1, new_visited) + + _ -> + false + end + end end end defp substitute_vars_canonical(spec, substitutions) do case spec do - {:type_var, name} -> Map.get(substitutions, name, spec) + {:type_var, name} -> + Map.get(substitutions, name, spec) + {:mu, var_name, body} -> active_substitutions = Map.delete(substitutions, var_name) {:mu, var_name, substitute_vars_canonical(body, active_substitutions)} + {:type_lambda, param_names, body} -> active_substitutions = Enum.reduce(param_names, substitutions, &Map.delete(&2, &1)) {:type_lambda, param_names, substitute_vars_canonical(body, active_substitutions)} - {:negation, sub} -> {:negation, substitute_vars_canonical(sub, substitutions)} - {:tuple, elements} -> {:tuple, Enum.map(elements, &substitute_vars_canonical(&1, substitutions))} - {:cons, h, t} -> {:cons, substitute_vars_canonical(h, substitutions), substitute_vars_canonical(t, substitutions)} - {:list_of, e} -> {:list_of, substitute_vars_canonical(e, substitutions)} - {:union, members} -> {:union, Enum.map(members, &substitute_vars_canonical(&1, substitutions))} - {:intersect, members} -> {:intersect, Enum.map(members, &substitute_vars_canonical(&1, substitutions))} + + {:negation, sub} -> + {:negation, substitute_vars_canonical(sub, substitutions)} + + {:tuple, elements} -> + {:tuple, Enum.map(elements, &substitute_vars_canonical(&1, substitutions))} + + {:cons, h, t} -> + {:cons, substitute_vars_canonical(h, substitutions), + substitute_vars_canonical(t, substitutions)} + + {:list_of, e} -> + {:list_of, substitute_vars_canonical(e, substitutions)} + + {:union, members} -> + {:union, Enum.map(members, &substitute_vars_canonical(&1, substitutions))} + + {:intersect, members} -> + {:intersect, Enum.map(members, &substitute_vars_canonical(&1, substitutions))} + {:type_apply, con, args} -> new_con = substitute_vars_canonical(con, substitutions) new_args = Enum.map(args, &substitute_vars_canonical(&1, substitutions)) {:type_apply, new_con, new_args} - _atomic_or_simple_spec -> spec + + _atomic_or_simple_spec -> + spec end end defp is_list_mu_form({:union, members}, rec_var_name) do sorted_members = Enum.sort(members) + match?([{:literal, []}, {:cons, _elem, {:type_var, ^rec_var_name}}], sorted_members) or - match?([{:cons, _elem, {:type_var, ^rec_var_name}}, {:literal, []}], sorted_members) + match?([{:cons, _elem, {:type_var, ^rec_var_name}}, {:literal, []}], sorted_members) end + defp is_list_mu_form(_, _), do: false defp extract_list_mu_element({:union, members}, rec_var_name) do Enum.find_value(members, fn {:cons, elem_spec, {:type_var, ^rec_var_name}} -> elem_spec _ -> nil - end) || :any + end) || :any end # Public API for get_supertypes @@ -572,6 +797,7 @@ defmodule Tdd.TypeSpec do {:integer_range, _, _} -> [:integer] _ -> [] end + MapSet.to_list(MapSet.new([fully_normalized_spec | supertypes])) end end @@ -1392,7 +1618,6 @@ defmodule Tdd.Algo do assumptions_imply_true and assumptions_imply_false -> Store.false_node_id() - # --- THIS IS THE FIX --- # If the context implies `var` must be true, we follow the 'yes' path. # We do NOT add `{var, true}` to the assumptions for the recursive call, # as that would cause the assumption set to grow infinitely and break @@ -1575,6 +1800,18 @@ defmodule Tdd.TypeReconstructor do top_level_assumptions = Map.get(partitions, :top_level, []) |> Map.new() top_level_spec = spec_from_flat_assumptions(top_level_assumptions) + # 2.5 Get implied base specs + implied_base_specs = + partitions + |> Map.keys() + |> Enum.map(fn + key when key in [:head, :tail] -> :list + {:elem, _} -> :tuple + # Other keys don't imply a base type + _ -> nil + end) + |> Enum.reject(&is_nil/1) + # 3. Recursively reconstruct specs for all sub-problems (head, tail, elements). sub_problem_specs = partitions @@ -1618,7 +1855,7 @@ defmodule Tdd.TypeReconstructor do end) # 4. The final spec is the intersection of the top-level spec and all sub-problem specs. - final_spec_list = [top_level_spec | sub_problem_specs] + final_spec_list = [top_level_spec | sub_problem_specs ++ implied_base_specs] TypeSpec.normalize({:intersect, final_spec_list}) end @@ -1694,14 +1931,18 @@ defmodule Tdd.Compiler do case Map.get(context, var_name) do nil -> raise "Tdd.Compiler: Unbound type variable during TDD compilation: #{inspect(var_name)}. Full spec: #{inspect(normalized_spec)}. Context: #{inspect(context)}" + placeholder_id when is_integer(placeholder_id) -> - placeholder_id # This is a placeholder ID for a mu-bound variable + # This is a placeholder ID for a mu-bound variable + placeholder_id end - _other_form -> # Not a top-level type variable, proceed with caching/compilation + # Not a top-level type variable, proceed with caching/compilation + _other_form -> case Store.get_op_cache(cache_key) do {:ok, id} -> id + :not_found -> id_to_cache = case normalized_spec do @@ -1732,14 +1973,16 @@ defmodule Tdd.Compiler do # are replaced by `compiled_body_id` itself. # The root of the mu-type's TDD is this new graph. final_id = Algo.substitute(compiled_body_id, placeholder_id, compiled_body_id) - + Algo.simplify(final_id) # Atomic types, literals, and compound types (union, intersect, etc.) _ -> - raw_id = do_structural_compile(normalized_spec, context) # Pass context for children's compilation + # Pass context for children's compilation + raw_id = do_structural_compile(normalized_spec, context) Algo.simplify(raw_id) end + Store.put_op_cache(cache_key, id_to_cache) id_to_cache end @@ -1751,19 +1994,34 @@ defmodule Tdd.Compiler do # It calls `compile_normalized_spec` for its children to ensure they are properly cached and mu/type_var handled. defp do_structural_compile(structural_spec, context) do case structural_spec do - :any -> Store.true_node_id() - :none -> Store.false_node_id() - :atom -> create_base_type_tdd(Variable.v_is_atom()) - :integer -> create_base_type_tdd(Variable.v_is_integer()) - :list -> create_base_type_tdd(Variable.v_is_list()) - :tuple -> create_base_type_tdd(Variable.v_is_tuple()) + :any -> + Store.true_node_id() + + :none -> + Store.false_node_id() + + :atom -> + create_base_type_tdd(Variable.v_is_atom()) + + :integer -> + create_base_type_tdd(Variable.v_is_integer()) + + :list -> + create_base_type_tdd(Variable.v_is_list()) + + :tuple -> + create_base_type_tdd(Variable.v_is_tuple()) {:literal, val} when is_atom(val) -> compile_value_equality(:atom, Variable.v_atom_eq(val), context) + {:literal, val} when is_integer(val) -> compile_value_equality(:integer, Variable.v_int_eq(val), context) - {:literal, []} -> # Empty list + + # Empty list + {:literal, []} -> compile_value_equality(:list, Variable.v_list_is_empty(), context) + # Add other literal types if necessary, e.g. literal tuples {:integer_range, min, max} -> @@ -1787,20 +2045,23 @@ defmodule Tdd.Compiler do {:cons, head_spec, tail_spec} -> id_head = compile_normalized_spec(head_spec, context) id_tail = compile_normalized_spec(tail_spec, context) - compile_cons_from_ids(id_head, id_tail, context) # context passed for sub_problem + # context passed for sub_problem + compile_cons_from_ids(id_head, id_tail, context) {:tuple, elements_specs} -> - compile_tuple_from_elements(elements_specs, context) # Renamed for clarity + # Renamed for clarity + compile_tuple_from_elements(elements_specs, context) # These should not be encountered here if TypeSpec.normalize worked correctly for ground types. {:type_lambda, _, _} -> raise "Tdd.Compiler: Cannot compile :type_lambda directly. Spec should be ground. Spec: #{inspect(structural_spec)}" + {:type_apply, _, _} -> raise "Tdd.Compiler: Cannot compile :type_apply directly. Spec should be ground and fully beta-reduced. Spec: #{inspect(structural_spec)}" # :mu and :type_var are handled by compile_normalized_spec directly. # :list_of is normalized to :mu by TypeSpec.normalize. - + # Catch-all for unexpected specs at this stage _ -> raise "Tdd.Compiler.do_structural_compile: Unhandled structural spec form: #{inspect(structural_spec)}" @@ -1811,7 +2072,13 @@ defmodule Tdd.Compiler do # Ensure they use `compile_normalized_spec` for sub-specs and pass `context`. defp create_base_type_tdd(var), - do: Store.find_or_create_node(var, Store.true_node_id(), Store.false_node_id(), Store.false_node_id()) + do: + Store.find_or_create_node( + var, + Store.true_node_id(), + Store.false_node_id(), + Store.false_node_id() + ) defp compile_value_equality(base_type_spec, value_var, context) do eq_node = create_base_type_tdd(value_var) @@ -1821,10 +2088,14 @@ defmodule Tdd.Compiler do end defp compile_integer_range(min, max, context) do - base_id = compile_normalized_spec(:integer, context) # Ensure :integer is compiled via main path + # Ensure :integer is compiled via main path + base_id = compile_normalized_spec(:integer, context) lt_min_tdd = if min != :neg_inf, do: create_base_type_tdd(Variable.v_int_lt(min)) - gte_min_tdd = if lt_min_tdd, do: Algo.negate(lt_min_tdd), else: compile_normalized_spec(:any, context) # Use :any for unbounded + # Use :any for unbounded + gte_min_tdd = + if lt_min_tdd, do: Algo.negate(lt_min_tdd), else: compile_normalized_spec(:any, context) + id_with_min = Algo.apply(:intersect, &op_intersect_terminals/2, base_id, gte_min_tdd) if max == :pos_inf do @@ -1838,23 +2109,28 @@ defmodule Tdd.Compiler do defp compile_cons_from_ids(h_id, t_id, context) do # TDD for `is_list & !is_empty` - id_list = compile_normalized_spec(:list, context) # Ensures :list is properly compiled + # Ensures :list is properly compiled + id_list = compile_normalized_spec(:list, context) id_is_empty = create_base_type_tdd(Variable.v_list_is_empty()) id_not_is_empty = Algo.negate(id_is_empty) - non_empty_list_id = Algo.apply(:intersect, &op_intersect_terminals/2, id_list, id_not_is_empty) + + non_empty_list_id = + Algo.apply(:intersect, &op_intersect_terminals/2, id_list, id_not_is_empty) head_checker = sub_problem(&Variable.v_list_head_pred/1, h_id, context) tail_checker = sub_problem(&Variable.v_list_tail_pred/1, t_id, context) [non_empty_list_id, head_checker, tail_checker] - |> Enum.reduce(compile_normalized_spec(:any, context), fn id, acc -> # Start intersection with :any + # Start intersection with :any + |> Enum.reduce(compile_normalized_spec(:any, context), fn id, acc -> Algo.apply(:intersect, &op_intersect_terminals/2, id, acc) end) end defp compile_tuple_from_elements(elements_specs, context) do size = length(elements_specs) - base_id = compile_normalized_spec(:tuple, context) # Ensures :tuple is properly compiled + # Ensures :tuple is properly compiled + base_id = compile_normalized_spec(:tuple, context) size_tdd = create_base_type_tdd(Variable.v_tuple_size_eq(size)) initial_id = Algo.apply(:intersect, &op_intersect_terminals/2, base_id, size_tdd) @@ -1874,12 +2150,18 @@ defmodule Tdd.Compiler do # is `compile_normalized_spec`. defp do_sub_problem(sub_key_constructor, tdd_id, context) do cond do - tdd_id < 0 -> # Should not happen with valid placeholder IDs + # Should not happen with valid placeholder IDs + tdd_id < 0 -> Store.false_node_id() + true -> case Store.get_node(tdd_id) do - {:ok, :true_terminal} -> Store.true_node_id() - {:ok, :false_terminal} -> Store.false_node_id() + {:ok, :true_terminal} -> + Store.true_node_id() + + {:ok, :false_terminal} -> + Store.false_node_id() + {:ok, {{:mu_placeholder_for_var, var_name_in_placeholder}, _, _, _}} -> # This is a placeholder node encountered during sub_problem traversal. # This means `tdd_id` is a `placeholder_id` for some `var_name`. @@ -1917,14 +2199,18 @@ defmodule Tdd.Compiler do # So `var` below would be `{:mu_placeholder_for_var, var_name_in_placeholder}`. raise "Tdd.Compiler.do_sub_problem: Encountered raw placeholder node details. This path needs review. Details: #{inspect(Store.get_node(tdd_id))}" - - {:ok, {var, y, n, d}} -> # Normal node + # Normal node + {:ok, {var, y, n, d}} -> Store.find_or_create_node( sub_key_constructor.(var), - sub_problem(sub_key_constructor, y, context), # Pass context - sub_problem(sub_key_constructor, n, context), # Pass context - sub_problem(sub_key_constructor, d, context) # Pass context + # Pass context + sub_problem(sub_key_constructor, y, context), + # Pass context + sub_problem(sub_key_constructor, n, context), + # Pass context + sub_problem(sub_key_constructor, d, context) ) + {:error, reason} -> raise "Tdd.Compiler.do_sub_problem: Error getting node for ID #{tdd_id}: #{reason}" end @@ -1935,9 +2221,14 @@ defmodule Tdd.Compiler do defp sub_problem(sub_key_constructor, tdd_id, context) do # Context is not part of cache key for sub_problem, as its effect is on how tdd_id was built. # The structure of tdd_id is what matters for sub_problem's transformation. - cache_key = {:sub_problem,Atom.to_string(elem(sub_key_constructor.(:dummy_var_for_cache_key),1)), tdd_id} + cache_key = + {:sub_problem, Atom.to_string(elem(sub_key_constructor.(:dummy_var_for_cache_key), 1)), + tdd_id} + case Store.get_op_cache(cache_key) do - {:ok, result_id} -> result_id + {:ok, result_id} -> + result_id + :not_found -> result_id = do_sub_problem(sub_key_constructor, tdd_id, context) Store.put_op_cache(cache_key, result_id) @@ -1945,7 +2236,6 @@ defmodule Tdd.Compiler do end end - # --- Terminal Logic Helpers (unchanged) --- defp op_union_terminals(:true_terminal, _), do: :true_terminal defp op_union_terminals(_, :true_terminal), do: :true_terminal @@ -2216,7 +2506,7 @@ defmodule TypeSpecTests do test( "Recursively normalizes element in list_of", - {:list_of, :list}, + {:mu, :m_var0, {:union, [{:literal, []}, {:cons, :list, {:type_var, :m_var0}}]}}, {:list_of, {:intersect, [:any, :list]}} ) @@ -3268,7 +3558,7 @@ defmodule Tdd.TypeSpecAdvancedTests do defp test(name, expected_spec, input_spec) do current_failures = Process.get(:test_failures, []) normalized_result = TypeSpec.normalize(input_spec) - is_equal = (expected_spec == normalized_result) + is_equal = expected_spec == normalized_result if is_equal do IO.puts("[PASS] #{name}") @@ -3284,6 +3574,7 @@ defmodule Tdd.TypeSpecAdvancedTests do # Test helper for checking raised errors (same as before) defp test_raise(name, expected_error_struct, expected_message_regex, input_spec) do current_failures = Process.get(:test_failures, []) + error_caught = try do TypeSpec.normalize(input_spec) @@ -3302,38 +3593,51 @@ defmodule Tdd.TypeSpecAdvancedTests do cond do is_nil(error_caught) -> IO.puts("[FAIL] #{name}") - IO.puts(" Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/") + + IO.puts( + " Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/" + ) + IO.puts(" Got: No error") Process.put(:test_failures, [name | current_failures]) match?({:unexpected_error, _}, error_caught) -> {:unexpected_error, e} = error_caught IO.puts("[FAIL] #{name} (Unexpected Error Type)") - IO.puts(" Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/") + + IO.puts( + " Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/" + ) + IO.puts(" Got error: #{inspect(e)}") Process.put(:test_failures, [name | current_failures]) - - (is_struct(error_caught, expected_error_struct) or - (is_tuple(error_caught) and elem(error_caught, 0) == expected_error_struct)) and - (is_nil(expected_message_regex) or String.match?(Exception.message(error_caught), expected_message_regex)) -> + + (is_struct(error_caught, expected_error_struct) or + (is_tuple(error_caught) and elem(error_caught, 0) == expected_error_struct)) and + (is_nil(expected_message_regex) or + String.match?(Exception.message(error_caught), expected_message_regex)) -> IO.puts("[PASS] #{name}") true -> IO.puts("[FAIL] #{name}") - IO.puts(" Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/") + + IO.puts( + " Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/" + ) + IO.puts(" Got error: #{inspect(error_caught)}") IO.puts(" Message: #{inspect(Exception.message(error_caught))}") Process.put(:test_failures, [name | current_failures]) end end - -def run() do - IO.puts("\n--- Running Tdd.TypeSpec Advanced Normalization Tests ---") + def run() do + IO.puts("\n--- Running Tdd.TypeSpec Advanced Normalization Tests ---") Process.put(:test_failures, []) # --- Section: μ-type (Recursive Type) Normalization --- IO.puts("\n--- Section: μ-type (Recursive Type) Normalization ---") + test( "basic alpha-conversion for μ-variable", {:mu, :m_var0, {:type_var, :m_var0}}, @@ -3342,10 +3646,11 @@ def run() do test( "alpha-conversion with nested μ-variable (depth-first renaming)", - {:mu, :m_var0, {:mu, :m_var1, {:union, [{:type_var, :m_var0}, {:type_var, :m_var1}]}}}, # Body union already sorted by var name + # Body union already sorted by var name + {:mu, :m_var0, {:mu, :m_var1, {:union, [{:type_var, :m_var0}, {:type_var, :m_var1}]}}}, {:mu, :X, {:mu, :Y, {:union, [{:type_var, :X}, {:type_var, :Y}]}}} ) - + test( "alpha-conversion order matters for canonical names (1)", # With subtype reduction deferred, both branches should survive pass1 and get canonical names. @@ -3353,20 +3658,27 @@ def run() do # Let's assume m1_spec sorts before m2_spec if they are different after canonical renaming. # Expected: m0 ( union(m1(m0|m1) , m2(m0|m2)) ) - sort order of m1_spec and m2_spec depends on their full structure. # Since :m_var1 and :m_var2 are the only difference, the one with :m_var1 comes first. - {:mu, :m_var0, {:union, [ - {:mu, :m_var1, {:union, [{:type_var, :m_var0}, {:type_var, :m_var1}]}}, # Inner union sorted - {:mu, :m_var2, {:union, [{:type_var, :m_var0}, {:type_var, :m_var2}]}} # Inner union sorted - ]}}, - {:mu, :A, {:union, [ - {:mu, :B, {:union, [{:type_var, :A}, {:type_var, :B}]}}, - {:mu, :C, {:union, [{:type_var, :A}, {:type_var, :C}]}} - ]}} + {:mu, :m_var0, + {:union, + [ + # Inner union sorted + {:mu, :m_var1, {:union, [{:type_var, :m_var0}, {:type_var, :m_var1}]}}, + # Inner union sorted + {:mu, :m_var2, {:union, [{:type_var, :m_var0}, {:type_var, :m_var2}]}} + ]}}, + {:mu, :A, + {:union, + [ + {:mu, :B, {:union, [{:type_var, :A}, {:type_var, :B}]}}, + {:mu, :C, {:union, [{:type_var, :A}, {:type_var, :C}]}} + ]}} ) test( "body of μ-type is normalized (sorted union, duplicates removed by final pass)", # apply_subtype_reduction will sort and unique the union members. - {:mu, :m_var0, {:union, [:integer, {:type_var, :m_var0}]}}, # :integer then :type_var + # :integer then :type_var + {:mu, :m_var0, {:union, [:integer, {:type_var, :m_var0}]}}, {:mu, :Rec, {:union, [:integer, {:type_var, :Rec}, :integer, :none]}} ) @@ -3382,18 +3694,22 @@ def run() do {:mu, :m_var0, {:union, [ - {:literal, []}, # Sorted first + # Sorted first + {:literal, []}, {:cons, - {:mu, :m_var1, - {:union, [{:literal, []}, {:cons, :atom, {:type_var, :m_var1}}]} # Inner sorted - }, - {:type_var, :m_var0}} + { + :mu, + :m_var1, + # Inner sorted + {:union, [{:literal, []}, {:cons, :atom, {:type_var, :m_var1}}]} + }, {:type_var, :m_var0}} ]}}, {:list_of, {:list_of, :atom}} ) # --- Section: Λ-type (Type Lambda) Normalization --- IO.puts("\n--- Section: Λ-type (Type Lambda) Normalization ---") + test( "basic alpha-conversion for Λ-parameters", {:type_lambda, [:lambda_var0], {:type_var, :lambda_var0}}, @@ -3402,7 +3718,8 @@ def run() do test( "multiple Λ-parameters alpha-converted (sorted by canonical name)", - {:type_lambda, [:lambda_var0, :lambda_var1], {:tuple, [{:type_var, :lambda_var0}, {:type_var, :lambda_var1}]}}, + {:type_lambda, [:lambda_var0, :lambda_var1], + {:tuple, [{:type_var, :lambda_var0}, {:type_var, :lambda_var1}]}}, {:type_lambda, [:K, :V], {:tuple, [{:type_var, :K}, {:type_var, :V}]}} ) @@ -3420,26 +3737,26 @@ def run() do {:tuple, [{:type_var, :lambda_var0}, {:type_var, :lambda_var1}]}}}, {:type_lambda, [:X], {:type_lambda, [:Y], {:tuple, [{:type_var, :X}, {:type_var, :Y}]}}} ) - + test( "lambda and mu interaction for canonical names", # Union body: {:type_var, :lambda_var0} sorts before {:type_var, :m_var0} - {:type_lambda, [:lambda_var0], - {:mu, :m_var0, {:union, [{:type_var, :lambda_var0}, {:type_var, :m_var0}]}}}, + {:type_lambda, [:lambda_var0], + {:mu, :m_var0, {:union, [{:type_var, :lambda_var0}, {:type_var, :m_var0}]}}}, {:type_lambda, [:T], {:mu, :X, {:union, [{:type_var, :T}, {:type_var, :X}]}}} ) test( "mu and lambda interaction for canonical names", # Union body: {:type_var, :lambda_var0} sorts before {:type_var, :m_var0} - {:mu, :m_var0, - {:type_lambda, [:lambda_var0], {:union, [{:type_var, :lambda_var0}, {:type_var, :m_var0}]}}}, + {:mu, :m_var0, + {:type_lambda, [:lambda_var0], {:union, [{:type_var, :lambda_var0}, {:type_var, :m_var0}]}}}, {:mu, :X, {:type_lambda, [:T], {:union, [{:type_var, :X}, {:type_var, :T}]}}} ) - # --- Section: Type Application Normalization (Beta-Reduction) --- IO.puts("\n--- Section: Type Application Normalization (Beta-Reduction) ---") + test( "simple application: (ΛT.T) integer -> integer", :integer, @@ -3456,8 +3773,7 @@ def run() do test( "application with multiple args: (ΛK,V. {K,V}) atom,integer -> {atom,integer}", {:tuple, [:atom, :integer]}, - {:type_apply, - {:type_lambda, [:K, :V], {:tuple, [{:type_var, :K}, {:type_var, :V}]}}, + {:type_apply, {:type_lambda, [:K, :V], {:tuple, [{:type_var, :K}, {:type_var, :V}]}}, [:atom, :integer]} ) @@ -3465,19 +3781,20 @@ def run() do "application resulting in a mu-type that needs further normalization after substitution", # Union: :integer then :type_var {:mu, :m_var0, {:union, [:integer, {:type_var, :m_var0}]}}, - {:type_apply, {:type_lambda, [:T], {:mu, :X, {:union, [{:type_var, :T}, {:type_var, :X}]}}}, [:integer]} + {:type_apply, {:type_lambda, [:T], {:mu, :X, {:union, [{:type_var, :T}, {:type_var, :X}]}}}, + [:integer]} ) test_raise( "arity mismatch in application raises error (too many args)", - RuntimeError, + RuntimeError, ~r/Arity mismatch/, {:type_apply, {:type_lambda, [:T], {:type_var, :T}}, [:integer, :atom]} ) - + test_raise( "arity mismatch in application raises error (too few args)", - RuntimeError, + RuntimeError, ~r/Arity mismatch/, {:type_apply, {:type_lambda, [:T, :U], {:type_var, :T}}, [:integer]} ) @@ -3493,29 +3810,30 @@ def run() do {:type_lambda, [:lambda_var0], {:tuple, [{:type_var, :Y_free}, {:type_var, :lambda_var0}]}}, ( y_free_spec = {:type_var, :Y_free} - inner_lambda = {:type_lambda, [:Y_bound], {:tuple, [{:type_var, :X}, {:type_var, :Y_bound}]}} + + inner_lambda = + {:type_lambda, [:Y_bound], {:tuple, [{:type_var, :X}, {:type_var, :Y_bound}]}} + outer_lambda = {:type_lambda, [:X], inner_lambda} {:type_apply, outer_lambda, [y_free_spec]} ) ) - + test( "application with nested lambdas and mus, complex substitution and renaming", # Expected: list_of(atom) normalized {:mu, :m_var0, {:union, [{:literal, []}, {:cons, :atom, {:type_var, :m_var0}}]}}, ( id_lambda = {:type_lambda, [:Tparam], {:type_var, :Tparam}} - list_lambda = {:type_lambda, [:Eparam], - {:list_of, {:type_var, :Eparam}} - } + list_lambda = {:type_lambda, [:Eparam], {:list_of, {:type_var, :Eparam}}} id_applied_to_atom = {:type_apply, id_lambda, [:atom]} {:type_apply, list_lambda, [id_applied_to_atom]} ) ) - # --- Section: Interaction with Union/Intersection --- IO.puts("\n--- Section: Interaction with Union/Intersection ---") + test( "union members are normalized with mu and apply (sorted result)", # :atom sorts before :integer @@ -3525,35 +3843,39 @@ def run() do # list_of_int_normalized will be {:mu, :m_var0, {:union, [{:literal, []}, {:cons, :integer, {:type_var, :m_var0}}]}} list_of_int_normalized = TypeSpec.normalize({:list_of, :integer}) + test( "list_of inside a union gets normalized and union sorted", # :atom sorts before {:mu, ...} {:union, [:atom, list_of_int_normalized]}, {:union, [:atom, {:list_of, :integer}]} ) - + test( "Normalization of type_apply within intersection, then intersection simplification", :integer, {:intersect, [:any, {:type_apply, {:type_lambda, [:T], {:type_var, :T}}, [:integer]}]} ) - # Final Report failures = Process.get(:test_failures, []) + if failures == [] do IO.puts("\n✅ All Tdd.TypeSpec Advanced Normalization tests passed!") else IO.puts("\n❌ Found #{length(failures)} Tdd.TypeSpec Advanced Normalization test failures:") Enum.each(Enum.reverse(failures), &IO.puts(" - #{&1}")) end + length(failures) == 0 end end + defmodule Tdd.CompilerAdvancedTests do alias Tdd.Compiler alias Tdd.Store - alias Tdd.TypeSpec # For constructing specs + # For constructing specs + alias Tdd.TypeSpec # Helper to run tests defp test(name, expected, actual_fun_call_result) do @@ -3575,9 +3897,10 @@ defmodule Tdd.CompilerAdvancedTests do defp test_equivalent_tdd(name, spec1, spec2) do id1 = Tdd.Compiler.spec_to_id(spec1) id2 = Tdd.Compiler.spec_to_id(spec2) - test(name, id1, id2) # Test that their TDD IDs are the same + # Test that their TDD IDs are the same + test(name, id1, id2) end - + defp test_compiles_to_none(name, spec) do id = Tdd.Compiler.spec_to_id(spec) test(name, Tdd.Store.false_node_id(), id) @@ -3590,14 +3913,18 @@ defmodule Tdd.CompilerAdvancedTests do defp test_raise_compile(name, expected_error_struct, expected_message_regex, input_spec) do current_failures = Process.get(:test_failures, []) + error_caught = try do Tdd.Compiler.spec_to_id(input_spec) - nil # No error + # No error + nil rescue e -> - if is_struct(e, expected_error_struct) or - (is_tuple(e) and elem(e,0) == expected_error_struct and expected_error_struct == RuntimeError) do # RuntimeError is {RuntimeError, %{message: "..."}} + # RuntimeError is {RuntimeError, %{message: "..."}} + if is_struct(e, expected_error_struct) or + (is_tuple(e) and elem(e, 0) == expected_error_struct and + expected_error_struct == RuntimeError) do e else {:unexpected_error, e} @@ -3607,33 +3934,50 @@ defmodule Tdd.CompilerAdvancedTests do cond do is_nil(error_caught) -> IO.puts("[FAIL] #{name}") - IO.puts(" Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/") + + IO.puts( + " Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/" + ) + IO.puts(" Got: No error") Process.put(:test_failures, [name | current_failures]) + match?({:unexpected_error, _}, error_caught) -> {:unexpected_error, e} = error_caught IO.puts("[FAIL] #{name} (Unexpected Error Type)") - IO.puts(" Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/") + + IO.puts( + " Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/" + ) + IO.puts(" Got error: #{inspect(e)}") Process.put(:test_failures, [name | current_failures]) - (is_struct(error_caught, expected_error_struct) or - (is_tuple(error_caught) and elem(error_caught, 0) == expected_error_struct and expected_error_struct == RuntimeError)) and - (is_nil(expected_message_regex) or String.match?(Exception.message(error_caught), expected_message_regex)) -> + + (is_struct(error_caught, expected_error_struct) or + (is_tuple(error_caught) and elem(error_caught, 0) == expected_error_struct and + expected_error_struct == RuntimeError)) and + (is_nil(expected_message_regex) or + String.match?(Exception.message(error_caught), expected_message_regex)) -> IO.puts("[PASS] #{name}") + true -> IO.puts("[FAIL] #{name}") - IO.puts(" Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/") + + IO.puts( + " Expected error: #{inspect(expected_error_struct)} matching ~r/#{inspect(expected_message_regex)}/" + ) + IO.puts(" Got error: #{inspect(error_caught)}") IO.puts(" Message: #{inspect(Exception.message(error_caught))}") Process.put(:test_failures, [name | current_failures]) end end - def run() do IO.puts("\n--- Running Tdd.Compiler Advanced Feature Tests (μ, Λ, Apply) ---") Process.put(:test_failures, []) - Tdd.Store.init() # Ensure store is fresh for each run module if tests are separate + # Ensure store is fresh for each run module if tests are separate + Tdd.Store.init() # --- Section: Basic μ-type compilation (via list_of normalization) --- IO.puts("\n--- Section: Basic μ-type (list_of) ---") @@ -3644,39 +3988,68 @@ defmodule Tdd.CompilerAdvancedTests do test_subtype("list_of(integer) <: list_of(any)", true, int_list, any_list) test_subtype("list_of(any) <: list_of(integer)", false, any_list, int_list) test_subtype("list_of(integer) <: list_of(atom)", false, int_list, atom_list) - + # Test equivalence of list_of(E) and its explicit μ unfolding # TypeSpec.normalize will convert list_of to mu. So this tests mu compilation. - list_of_int_norm = TypeSpec.normalize(int_list) # This is already {:mu, :m_var0, ...} - test_equivalent_tdd("list_of(int) TDD is equivalent to its normalized mu-form TDD", int_list, list_of_int_norm) + # This is already {:mu, :m_var0, ...} + list_of_int_norm = TypeSpec.normalize(int_list) + + test_equivalent_tdd( + "list_of(int) TDD is equivalent to its normalized mu-form TDD", + int_list, + list_of_int_norm + ) test_subtype("[] <: list_of(integer)", true, {:literal, []}, int_list) - test_subtype("cons(1, []) <: list_of(integer)", true, {:cons, {:literal, 1}, {:literal, []}}, int_list) - test_subtype("cons(:a, []) !<: list_of(integer)", false, {:cons, {:literal, :a}, {:literal, []}}, int_list) - test_subtype("cons(1, cons(:a, [])) !<: list_of(integer)", false, {:cons, {:literal, 1}, {:cons, {:literal, :a}, {:literal, []}}}, int_list) + # Tdd.Debug.run(fn -> + test_subtype( + "cons(1, []) <: list_of(integer)", + true, + {:cons, {:literal, 1}, {:literal, []}}, + int_list + ) + # end) + test_subtype( + "cons(:a, []) !<: list_of(integer)", + false, + {:cons, {:literal, :a}, {:literal, []}}, + int_list + ) + + test_subtype( + "cons(1, cons(:a, [])) !<: list_of(integer)", + false, + {:cons, {:literal, 1}, {:cons, {:literal, :a}, {:literal, []}}}, + int_list + ) # --- Section: Explicit μ-types --- IO.puts("\n--- Section: Explicit μ-types ---") # Binary Tree of Atoms: Tree = μX. (Empty | Node) # Using :empty_tree for the literal leaf for clarity. leaf_node = {:literal, :empty_tree} - tree_spec = {:mu, :Tree, {:union, [ - leaf_node, - {:tuple, [:atom, {:type_var, :Tree}, {:type_var, :Tree}]} - ]}} - + + tree_spec = + {:mu, :Tree, + {:union, + [ + leaf_node, + {:tuple, [:atom, {:type_var, :Tree}, {:type_var, :Tree}]} + ]}} + # Check it compiles without error first _tree_tdd_id = Tdd.Compiler.spec_to_id(tree_spec) test("Explicit mu-type (atom tree) compiles", true, is_integer(_tree_tdd_id)) # An instance of the tree - simple_tree_instance = {:tuple, [{:literal, :a }, leaf_node, leaf_node]} + simple_tree_instance = {:tuple, [{:literal, :a}, leaf_node, leaf_node]} test_subtype("Simple atom tree instance <: AtomTree", true, simple_tree_instance, tree_spec) - non_tree_instance = {:tuple, [{:literal, 123 }, leaf_node, leaf_node]} # Integer instead of atom + # Integer instead of atom + non_tree_instance = {:tuple, [{:literal, 123}, leaf_node, leaf_node]} test_subtype("Non-atom tree instance ; Odd = Succ # Let's use a simpler form: Stream = μS. cons(T, S) @@ -3684,12 +4057,17 @@ defmodule Tdd.CompilerAdvancedTests do _int_stream_id = Tdd.Compiler.spec_to_id(int_stream_spec) test("μ-type for int stream compiles", true, is_integer(_int_stream_id)) - test_subtype("cons(1, cons(2, Stream)) <: Stream", true, - {:cons, {:literal, 1}, {:cons, {:literal, 2}, int_stream_spec}}, + test_subtype( + "cons(1, cons(2, Stream)) <: Stream", + true, + {:cons, {:literal, 1}, {:cons, {:literal, 2}, int_stream_spec}}, int_stream_spec ) - test_subtype("cons(:a, Stream) # This should normalize to the same spec as list_of(integer) list_of_int_from_apply = {:type_apply, gen_list_lambda, [:integer]} + test_equivalent_tdd( "(ΛT. list_of(T)) TDD == list_of(integer) TDD", list_of_int_from_apply, - int_list # which is {:list_of, :integer} + # which is {:list_of, :integer} + int_list ) # Apply to atom: GenList list_of_atom_from_apply = {:type_apply, gen_list_lambda, [:atom]} + test_equivalent_tdd( "(ΛT. list_of(T)) TDD == list_of(atom) TDD", list_of_atom_from_apply, - atom_list # which is {:list_of, :atom} + # which is {:list_of, :atom} + atom_list ) # Test subtyping between instantiated types @@ -3733,55 +4115,64 @@ defmodule Tdd.CompilerAdvancedTests do # Identity function: ID = ΛT. T id_lambda = {:type_lambda, [:T], {:type_var, :T}} - id_applied_to_atom = {:type_apply, id_lambda, [:atom]} # Normalizes to :atom + # Normalizes to :atom + id_applied_to_atom = {:type_apply, id_lambda, [:atom]} test_equivalent_tdd("(ΛT.T) TDD == :atom TDD", id_applied_to_atom, :atom) # --- Section: Error Handling in Compiler --- IO.puts("\n--- Section: Error Handling in Compiler ---") - + test_raise_compile( "Compiling a raw :type_lambda errors", - RuntimeError, ~r/Cannot compile :type_lambda directly/, - {:type_lambda, [:T], {:type_var, :T}} # This is already normalized + RuntimeError, + ~r/Cannot compile :type_lambda directly/, + # This is already normalized + {:type_lambda, [:T], {:type_var, :T}} ) # TypeSpec.normalize will leave this as is if F is free. test_raise_compile( "Compiling an unreduced :type_apply (with free constructor var) errors", - RuntimeError, ~r/Cannot compile :type_apply directly/, + RuntimeError, + ~r/Cannot compile :type_apply directly/, {:type_apply, {:type_var, :F}, [:integer]} ) - + # An unbound type variable not bound by any mu # Normalization will keep {:type_var, :Unbound} as is if it's free. # The error should come from `compile_normalized_spec` for the `{:type_var, name}` case. test_raise_compile( "Compiling an unbound :type_var errors", - RuntimeError, ~r/Unbound type variable/, + RuntimeError, + ~r/Unbound type variable/, {:type_var, :SomeUnboundVar} ) - + # A :type_var that is bound by a mu, but the mu is inside a lambda that isn't applied. # e.g. ΛT. (μX. X) -- this is fine to normalize. Compiling it is an error. spec_lambda_mu_var = {:type_lambda, [:T], {:mu, :X, {:type_var, :X}}} + test_raise_compile( "Compiling lambda containing mu (still a lambda) errors", - RuntimeError, ~r/Cannot compile :type_lambda directly/, + RuntimeError, + ~r/Cannot compile :type_lambda directly/, spec_lambda_mu_var ) - # Final Report failures = Process.get(:test_failures, []) + if failures == [] do IO.puts("\n✅ All Tdd.Compiler Advanced Feature tests passed!") else IO.puts("\n❌ Found #{length(failures)} Tdd.Compiler Advanced Feature test failures:") Enum.each(Enum.reverse(failures), &IO.puts(" - #{&1}")) end + length(failures) == 0 end end + Process.sleep(100) TypeSpecTests.run() TddStoreTests.run()