package cd.ir;


import cd.ir.Ast.Expr;
import cd.ir.Symbol.PrimitiveTypeSymbol;

import java.util.Map;

/**
 * A visitor that replaces AST nodes in toBeReplaced
 * used in ConstantAnalysis, deletes all the variables that have a constant value and replace them with a constant
 */

public class AstReplaceVisitor extends AstRewriteVisitor<Ast> {

	// use this information to replace each Var node with it's correct constant value
	public Map<Ast.Expr, Ast.LeafExpr> toBeReplaced;
	public Map<Expr, Integer> initializePositions;
	public int currentPosition;


	public Ast.LeafExpr getReplacement(Ast.Var arg) {

		// Var was declared constant but initialization happens later
		// replace it with IntConst or BooleanConst and their default value
		if (toBeReplaced.containsKey(arg) && currentPosition <= initializePositions.get(arg)) {
			//if (toBeReplaced.containsKey(arg)) {
			Ast.LeafExpr leafEpr = (Ast.LeafExpr) arg;
			if (leafEpr.type == PrimitiveTypeSymbol.intType) {
				return new Ast.IntConst(0);
			} else {
				return new Ast.BooleanConst(false);
			}
		}
		// Var was declared constant and initialization already happened
		else if (toBeReplaced.containsKey(arg) && currentPosition > initializePositions.get(arg)) {
			return toBeReplaced.get(arg);
		}
		// Var was not declared to be a constant
		else {
			return arg;
		}
	}


	public Ast var(Ast.Var ast, Void arg) {
		return getReplacement(ast);
	}


}
