package cd.transform.analysis;

import cd.ir.Ast;
import cd.ir.Ast.ClassDecl;
import cd.ir.AstVisitor;
import cd.ir.BasicBlock;
import cd.ir.Symbol.ClassSymbol;
import cd.ir.Symbol.MethodSymbol;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class StaticMethodUsage extends AstVisitor<Void, Set<MethodSymbol>> {

	public Set<MethodSymbol> go(List<ClassDecl> classDecls) {
		Set<MethodSymbol> usedMethods = new HashSet<>();

		for (ClassDecl classDecl : classDecls) {
			if (classDecl.name.equals("Main")) {
				Ast.MethodDecl mainMethod = classDecl.sym.getMethod("main").ast;
				for (BasicBlock block : mainMethod.cfg.allBlocks) {
					block.accept(this, usedMethods);
				}
			}
		}

		return usedMethods;
	}

	@Override
	public Void methodCall(Ast.MethodCall ast, Set<MethodSymbol> arg) {
		ClassSymbol classSym = (ClassSymbol) ast.getMethodCallExpr().receiver().type;
		MethodSymbol method = classSym.getMethod(ast.getMethodCallExpr().methodName);
		arg.add(method);
		visit(method.ast, arg);
		return null;
	}
}
