from CompNode import CompNode
from pprint import pprint
from Environment import GlobalEnv

# tree: (filename, parseTree)
def astBuild(trees):
    ASTs = []
    for (n, t) in trees:
        ASTs.append((n, CompNode(t)))
    return ASTs

def buildEnvAndLink(ASTs):
    # build env
    globalEnv = GlobalEnv()
    for t in ASTs:
        globalEnv.addtoEnv(t[1])

    # print ("\n\n###################### global Env ####################")
    # pprint(vars(globalEnv))
    globalEnv.weedGlobalEnv()

    for t in ASTs:
        try:
            t[1].recurseBuildEnv(globalEnv)
        except Exception as e: # to handle double local variable declaration
            raise e
        # print('\n\n\n', t[0])
        # print("###################### Comp Unit Env ####################")
        # t[1].recurseAction("printEnv")


    # type Linking
    for t in ASTs:
        t[1].recurseAction("linkType")

    # hierarchy checking
    for t in ASTs:
        t[1].recurseAction("checkHierarchy")

#######################################################

def disamiguateAndTypeChecking(ASTs):

    # disambiguate namespace: figuring out the meaning of the shortest prefix of names 
    for t in ASTs:
        t[1].disambigName()
    
    # type checking
    for t in ASTs:
        t[1].checkType()

    # resolving the rest of the name

#######################################################

def reachabilityChecking(ASTs):
    for t in ASTs:
        t[1].reachCheck()

    # for t in ASTs:
    #     t[1].staticAnalysis()