/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package IntermediaryCode;

import API.Instruction;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;

/**
 *
 * @author EUGENIO CARVALHO
 */
class CodeClearProcessor implements CodeProcessing {

    public CodeClearProcessor() {
    }

    @Override
    public void Exec(Code c, LinkedHashMap<String, CodeProcessing> cp) throws Exception {
        String label;
        Instruction instruction;
        Block block = c.Block();
        HashMap<String, Integer> rc = c.labelsReferenceCount;
        Iterator<Instruction> interator = block.Instructions().iterator();
        String[] ignore = new String[]{"block", "user"};
        // Remove todos os labels não referenciados
        while (interator.hasNext()) {
            instruction = interator.next();

//            System.out.println("instruction:" + instruction);
            if (!instruction.eq("type", "label") || instruction.in("label_type", ignore)) {
                continue;
            }

            label = instruction.G("label");
            if (!rc.containsKey(label) || rc.get(label) == 0) {
                interator.remove();
            }
        }
    }
}
