view python/c3/builder.py @ 254:bd26dc13f270

Added logger
author Windel Bouwman
date Wed, 31 Jul 2013 21:20:58 +0200
parents 6ed3d3a82a63
children 7416c923a02a
line wrap: on
line source

import logging
import ppci
from . import Parser, TypeChecker, Analyzer, CodeGenerator
from . astprinter import AstPrinter
import glob

class Builder:
    """ 
        Generates IR-code from c3 source.
        Reports errors to the diagnostics system
    """
    def __init__(self, diag):
        self.logger = logging.getLogger('c3')
        self.diag = diag
        self.parser = Parser(diag)
        self.tc = TypeChecker(diag)
        self.al = Analyzer(diag)
        self.cg = CodeGenerator()
        self.packages = {}

    def getPackage(self, pname):
        """ package provider for use when analyzing """
        if pname in self.packages:
            return self.packages[pname]
        else:
            # Try to lookup package from file
            fns = glob.glob('./*/{}.c3'.format(pname))
            if fns:
                with open(fns[0]) as f:
                    src = f.read()
                self.build(src)
            if pname in self.packages:
                return self.packages[pname]

    def parse(self, src):
        pkg = self.parser.parseSource(src)
        if not pkg:
            return
        logging.getLogger('c3').info('Source parsed')

        # TODO: merge the two below?
        #AstPrinter().printAst(pkg)
        if not self.al.analyzePackage(pkg, self):
            return
        if not self.tc.checkPackage(pkg):
            return

        # Store for later use:
        self.packages[pkg.name] = pkg
        return pkg

    def build(self, src):
        """ Create IR-code from sources """
        pkg = self.parse(src)

        # Only return ircode when everything is OK
        if pkg:
            return self.cg.gencode(pkg)