%%% This file is part of RefactorErl.
%%%
%%% RefactorErl is free software: you can redistribute it and/or modify
%%% it under the terms of the GNU Lesser General Public License as published
%%% by the Free Software Foundation, either version 3 of the License, or
%%% (at your option) any later version.
%%%
%%% RefactorErl is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%%% GNU Lesser General Public License for more details.
%%%
%%% You should have received a copy of the GNU Lesser General Public License
%%% along with RefactorErl.  If not, see <http://plc.inf.elte.hu/erlang/>.
%%%
%%% The Original Code is RefactorErl.
%%%
%%% The Initial Developer of the Original Code is Eötvös Loránd University.
%%% Portions created  by Eötvös Loránd University and ELTE-Soft Ltd.
%%% are Copyright 2007-2025 Eötvös Loránd University, ELTE-Soft Ltd.
%%% and Ericsson Hungary. All Rights Reserved.


%%% ============================================================================
%%% Module information

%%% @doc This  module  compares  variables  of  an Erlang  syntax  tree to a
%%% RefactorErl database.

%%% @author Ely Deckers <e.deckers@student.ru.nl>

-module(refqc_tc_vars).

-vsn("$Rev: 17551 $").

-include_lib("referl_qc/include/qc.hrl").

-export([referl_eq/2]).

-author("Ely Deckers <e.deckers@student.ru.nl>").

%% @spec referl_eq(Scope::list(),VarNode::syntaxTree()) -> bool()
%%
%% @doc Verify that a particular variable exists in the Referl database and it's
%% semantically equivalent to the Erlang Syntax tree.
referl_eq(Scope,VarNode) ->
    ?QCTCLOG:writepath("?QCTCVAR:referl_eq",Scope,VarNode),

    NamesEqual = compare_var_names(Scope,VarNode),

    %If variable names are the same, check their semantic equality
    if NamesEqual ->
        VarSubTrees = erl_syntax:subtrees(VarNode),
        compare_var_values(Scope,VarSubTrees);
    true ->
        false
    end.

%% @spec compare_var_names(Scope::list(),VarNode::syntaxTree()) -> bool()
%%
%% @doc Verify that two Variables have the same name (in RefErl and
%% Erlang trees).
compare_var_names(Scope,VarNode) ->
    {_,_,ReferlName} = Scope,
    ErlName = atom_to_list(erl_syntax:variable_name(VarNode)),

    (ErlName == ReferlName).

%% @spec compare_var_values(Scope,syntax_tree()) -> true | false
%%
%% @doc Verify that two Variable values are equal (in RefErl and
%% Erlang trees).
compare_var_values(Scope,VarSubTrees) when is_list(VarSubTrees) ->
    ?QCTCCOMPARE:traverse(Scope,VarSubTrees);
compare_var_values(Scope,VarSubTrees) ->
    ?QCTCCOMPARE:traverse(Scope,[VarSubTrees]).
