コード例 #1
0
    def resolveDestination(self, invocation):
        resolutionReport = invocation.getReport()

        uniqueName = invocation.dst_name

        # don't spend time looking for methods or functions
        # that are totally unknown
        if not self.invEntityDict.hasMultiLocKey(uniqueName):
            return False

        resolutionReport.setDestinationNameKnown()

        if invocation.dst_class != "":
            uniqueName = invocation.dst_class + "." + invocation.dst_name

        refLoc = SourceLocation(invocation.sourceFile, invocation.start,
                                invocation.start)

        # ensure that # is not regarded as a class name
        if (invocation.dst_class == "#"):
            invocation.dst_class = ""

        selection = self.resolver.select(invocation.dst_class,
                                         invocation.dst_name,
                                         invocation.actualDstParams, refLoc,
                                         invocation.src_class)

        if not selection:
            return False
        elif len(selection) > 1:
            # TODO: indien references file gesorteerd op lijn en karakter
            # dan kan je alsnog een resolution aanbieden indien er slechts 1
            # access was en geen andere invocaties op die lijn verwerkt werden
            # de dst_class is dan het type van het attribuut
            resolutionReport.setNumberOfFoundDestinations(len(selection))
            return False

        resolutionReport.setNumberOfFoundDestinations(1)

        # merely one invokable entity
        invokableEntityRef = selection[0]
        multiLoc = invokableEntityRef.getLocation()

        declarationDefinitionTuples = multiLoc.getIncludedDeclarationDefinitionTuples(
            self.scope, refLoc.getSourceFile())
        if not declarationDefinitionTuples:
            return False
        elif len(declarationDefinitionTuples) > 1:
            resolutionReport.setNumberOfIncludedDestinations(
                len(declarationDefinitionTuples))
            return False

        resolutionReport.setNumberOfIncludedDestinations(1)

        # merely one declaration-definition tuple
        declLoc = declarationDefinitionTuples[0][
            0]  # retrieve first location from single tuple
        self.fillInInvocationDestination(invocation, invokableEntityRef,
                                         declLoc)
        return True
コード例 #2
0
ファイル: javaEntities.py プロジェクト: carvalhomb/tsmells
    def resolvePackage(self, pkgDict, classDict, mtdpfDict):
        #srcSourceFiles = classDict.getSourceLocations(self.src_class)
        # std. scenario
        #if 1 == len(srcSourceFiles):
        #	srcSourceFile = srcSourceFiles[0][0]
        #	srcStart = srcSourceFiles[0][1]
        #	self.srcSourceLocation = SourceLocation(srcSourceFile, srcStart, srcStart)
        #	pkg = pkgDict.getPackageForFile(self.sourceFile)
        #	if pkg: self.src_class = pkg + "::" + self.src_class
        #elif 0 == len(srcSourceFiles):
        #	self.log.warn(	"No sourceLocation for attribute owner: "+\
        #					self.src_class)
        #else:
        #	self.log.warn("Multiple sourceLocations for attribute owner: "+\
        #					self.src_class+": ",srcSourceFiles)

        resolvMtd, srcStart = mtdpfDict.getEnclosing(self.sourceFile,
                                                     self.lineNr)
        if not resolvMtd:
            self.log.warn("Could not find the method containing " +
                          self.lineNr + " in " + self.sourceFile)
            return

        if not self.src_name in resolvMtd:
            # might use class location for this
            self.log.warn("Resolved enclosing method differs SN dump. [SN:" +\
                 self.src_name + "<> em:" + resolvMtd + "]")
        elif not self.src_class in resolvMtd:  # fully qualified
            self.log.warn("Enclosed class differs from SN dump [SN:" +\
                 self.src_class + "<> ec:" + resolvMtd + "]")
        else:
            self.srcSourceLocation = SourceLocation(self.sourceFile,
                                                    str(srcStart),
                                                    str(srcStart))
            pkg = pkgDict.getPackageForFile(self.sourceFile)
            if pkg:
                self.src_class = pkg + "::" + self.src_class

        # for destination
        dstSrcFiles = classDict.getSourceLocations(self.dst_class)
        if 1 == len(dstSrcFiles):
            # std. scenario
            dstSourceFile = dstSrcFiles[0][0]
            dstStart = dstSrcFiles[0][1]
            self.dstSourceLocation = SourceLocation(dstSourceFile, dstStart,
                                                    dstStart)
            pkg = pkgDict.getPackageForFile(dstSourceFile)
            if pkg: self.dst_class = pkg + "::" + self.dst_class

        else:
            # todo check options, such as incorporating import information
            self.log.warn("Could not resolve destination:" + self.dst_class)
コード例 #3
0
ファイル: ClassEntity.py プロジェクト: carvalhomb/tsmells
    def getReference(self):
        reference = TypeDefEntityReference()

        reference.setBaseType(self.baseType)
        reference.setName(self.aliasName)
        sourceLocation = SourceLocation(self.sourceFile, self.start,
                                        self.start)
        reference.setSourceLocation(sourceLocation)
        baseSourceLocation = SourceLocation(self.baseSourceFile,
                                            self.baseLineNr, self.baseLineNr)
        reference.setBaseSourceLocation(baseSourceLocation)

        return reference
コード例 #4
0
ファイル: javaEntities.py プロジェクト: carvalhomb/tsmells
 def __init__(self, line):
     self.log = Logger().get_instance(self)
     self.cols = line.split(";")
     self.dst_class = self.cols[0]
     self.dst_name = self.cols[1]
     self.src_class = self.cols[3]
     self.src_name = self.cols[4]
     self.acc_type = self.cols[5]
     self.sourceFile = self.cols[8]
     self.lineNr = utils.removeUpfrontZeroes(self.cols[7])
     self.src_param = utils.cleanCol(self.cols[10].strip()).split(",")
     self.package = ""
     self.srcSourceLocation = SourceLocation("", "0", "0")
     self.dstSourceLocation = SourceLocation("", "0", "0")
コード例 #5
0
ファイル: javaEntities.py プロジェクト: carvalhomb/tsmells
    def __init__(self, line):
        self.log = Logger().get_instance(self)
        self.cols = line.split(";")
        self.owner = self.cols[0]
        self.name = self.cols[1] + "(" + utils.cleanCol(self.cols[7]) + ")"

        sourceFile = self.cols[3]
        lineNr = self.cols[4].split(".")[0]
        self.sourceLocation = SourceLocation(sourceFile, lineNr, lineNr)

        self.isConstructor = False
        # TODO: parse visibility codes
        self.accessControlQualifier = "public"
        # TODO: static?
        self.hasClassScope = False
        # TODO: abstract? Interface?
        self.isAbstract = False
        params = self.cols[7]
        if "{}" == params:
            self.parameters = []
            self.parameterNames = []
        else:
            self.parameters = utils.cleanCol(params).split(",")
            self.parameterNames = utils.cleanCol(self.cols[8]).split(",")

        # to be resolved later
        self.package = None
        self.retType = None
        self.parentType = None
        # scope, visibility, abstract
        self.__resolveCharacteristics(self.cols[5])
コード例 #6
0
ファイル: ClassEntity.py プロジェクト: carvalhomb/tsmells
 def determineSourceLocation(self):
     # Bar;000001.006;src/AbstractClass.cpp;1.9;0x0;{};{};{};{}
     # the old way -- to be removed
     sourceFile = self.cols[2]
     start = self.cols[3].split(".")[0]
     # the new way
     self.sourceLocation = SourceLocation(sourceFile, start, start)
コード例 #7
0
	def resolveSource(self, invOrAccess):
		resolutionReport = invOrAccess.getReport()

		refLoc = SourceLocation(invOrAccess.sourceFile, invOrAccess.start, invOrAccess.start)

		invokableEntityRef = None

		if self.inCache(refLoc):
			invokableEntityRef = self.getSurroundingDefinitionFromCache(refLoc)
		else:
			# ensure that # is not regarded as a class name
			if ( invOrAccess.src_class == "#" ):
				invOrAccess.src_class = ""

			invokableEntityRef = self.getSurroundingDefinition(invOrAccess, refLoc)

		if invokableEntityRef == None:
			return False

		resolutionReport.setSurroundingDefinitionFound()

		defLoc = self.getDefinitionLocation(invokableEntityRef, refLoc)
		if defLoc == None:
			return False

		resolutionReport.setDefinitionLocationFound()

		self.fillInReferenceSource(invOrAccess, invokableEntityRef, defLoc)
		return True
コード例 #8
0
ファイル: javaEntities.py プロジェクト: carvalhomb/tsmells
 def getReference(self):
     reference = NamespaceEntityReference()
     reference.setName(self.name)
     sourceLocation = SourceLocation(self.sourceFile, \
            self.lineNr, \
            self.lineNr)
     reference.addSourceLocation(sourceLocation)
     return reference
コード例 #9
0
	def getReference(self):
		reference = ClassUsageReference()
		reference.setName(self.getNamespaceName())
		sourceLocation = SourceLocation(self.getDeclaringFileName(), \
									self.getStartLineNumber(), \
									self.getEndLineNumber())
		reference.addSourceLocation(sourceLocation)
		return reference
コード例 #10
0
    def getSurroundingNamespaceList(self, fileName, lineNr):
        parentNamespaceList = []

        location = SourceLocation(fileName, lineNr, lineNr)

        if self.namespaceDict.fileInDictionary(fileName):
            for reference in self.namespaceDict.getReferences(fileName):
                if reference.surroundsLocation(location):
                    parentNamespaceList.append(reference)

        return parentNamespaceList
コード例 #11
0
	def resolveDestination(self, invocation):
		resolutionReport = invocation.getReport()

		uniqueName = invocation.dst_name

		# don't spend time looking for methods or functions
		# that are totally unknown
		if not self.invEntityDict.hasMultiLocKey(uniqueName):
			return False

		resolutionReport.setDestinationNameKnown()

		if invocation.dst_class != "":
			uniqueName = invocation.dst_class + "." + invocation.dst_name

		refLoc = SourceLocation(invocation.sourceFile, invocation.start, invocation.start)

		# ensure that # is not regarded as a class name
		if ( invocation.dst_class == "#" ):
			invocation.dst_class = ""

		selection = self.resolver.select(invocation.dst_class, invocation.dst_name, invocation.actualDstParams, refLoc, invocation.src_class)

		if not selection:
			return False
		elif len(selection) > 1:
			# TODO: indien references file gesorteerd op lijn en karakter
			# dan kan je alsnog een resolution aanbieden indien er slechts 1
			# access was en geen andere invocaties op die lijn verwerkt werden
			# de dst_class is dan het type van het attribuut
			resolutionReport.setNumberOfFoundDestinations(len(selection))
			return False

		resolutionReport.setNumberOfFoundDestinations(1)

		# merely one invokable entity
		invokableEntityRef = selection[0]
		multiLoc = invokableEntityRef.getLocation()

		declarationDefinitionTuples = multiLoc.getIncludedDeclarationDefinitionTuples(self.scope, refLoc.getSourceFile())
		if not declarationDefinitionTuples:
			return False
		elif len(declarationDefinitionTuples) > 1:
			resolutionReport.setNumberOfIncludedDestinations(len(declarationDefinitionTuples))
			return False

		resolutionReport.setNumberOfIncludedDestinations(1)

		# merely one declaration-definition tuple
		declLoc = declarationDefinitionTuples[0][0] # retrieve first location from single tuple
		self.fillInInvocationDestination(invocation, invokableEntityRef, declLoc)
		return True
コード例 #12
0
def parseGlobalVars(globalVarDBD, namespaceContainmentChecker, classSelector):
	#global namespaceContainmentChecker
	for line in open(globalVarDBD, 'r'):
		gv = GlobalVariableEntity(line)
		gvRef = gv.getReference()
		
		sourceLoc = SourceLocation(gvRef.getSourceFile(),\
                                        gvRef.getLineNr(),\
                                        gvRef.getLineNr())
		namespaceName = namespaceContainmentChecker.getSurroundingNamespaceName(sourceLoc)
		
		gv.namespaceName = namespaceName
		gvRef = gv.getReference() # TODO: refactor reference as to be a true updateable instance,
                                  # in that case it would be sufficient to state
                                  # gv.setNamespaceName(namespaceName)


		# resolve the global variable type
		typeRef = gv.getTypeReference()
		
		if not(typeRef.isPrimitive()):
			potentialTargets = classSelector.selectClasses(typeRef.getCleanName(),\
                                                     gvRef.getSourceFile(), gvRef.getLineNr())
			nrOfTargets = len(potentialTargets)
			
			if ( nrOfTargets > 1 ):
				pass
				#log.warn("GlobalVariable-type-problem: ",nrOfTargets," classes with name \""\
				#         + typeRef.getReferencedName() + ".")
				typeRef.setResolvedName(typeRef.getCleanName())
			elif ( nrOfTargets == 0 ):
				pass
				#log.warn("GlobalVariable-type-problem: no class with name \"" \
				#        + typeRef.getReferencedName() + "\" known from file ",\
				#        gvRef.getSourceFile(),"@",gvRef.getLineNr(),".")
				typeRef.setResolvedName(typeRef.getCleanName())
			else:
				# get the data on the sole left-over method-type
				classReference = potentialTargets[0]
				
				typeRef.setResolvedName(classReference.getUniqueName())
				typeRef.setSourceFile(classReference.getSourceFile())
				typeRef.setLineNr(classReference.getLineNr())

				# TODO: fill in the global variable type template parameters
		else:
			typeRef.setResolvedName(typeRef.getCleanName())
		
		# extract this in a processing method.
		if typeRef.getReferencedName() != "":
			common.famix.cdifWriter.generateGlobalVarInfo(gv)
コード例 #13
0
ファイル: javaEntities.py プロジェクト: carvalhomb/tsmells
    def resolveSuperClass(self, pkgDict, classDict):
        """ resolves the fully qualified super class """
        if self.superclass.find("::") != -1:
            # qualified SN deficiency
            superSourceFile = self.superclass.replace("::", "/") + ".java"
            superSourceFiles = classDict.getSourceLocations(
                self.superclass.split("::")[-1])
            for srcLoc in superSourceFiles:
                if srcLoc[0] == superSourceFile:
                    self.superSourceLocation = SourceLocation(
                        superSourceFile, srcLoc[1], srcLoc[1])
                    return

        superSourceFiles = classDict.getSourceLocations(self.superclass)

        # std. scenario
        if 1 == len(superSourceFiles):
            superSourceFile = superSourceFiles[0][0]
            superStart = superSourceFiles[0][1]
            self.superSourceLocation = \
               SourceLocation(superSourceFile, superStart, superStart)
            pkg = pkgDict.getPackageForFile(superSourceFile)
            if "" != pkg:
                self.superclass = pkg + "::" + self.superclass
        elif 0 == len(superSourceFiles):
            self.log.warn( "No source locations for superclass "+\
                self.superclass +\
                " of subclass " +\
                self.getQualSubclass())
            self.superSourceLocation = SourceLocation("", "0", "0")
        else:
            self.log.warn( "Multiple source locations for superclass "+\
                self.superclass+": ",superSourceFiles,\
                " of subclass " +\
                self.getQualSubclass())
            self.superSourceLocation = SourceLocation("", "0", "0")
コード例 #14
0
ファイル: javaEntities.py プロジェクト: carvalhomb/tsmells
    def __init__(self, line):
        self.log = Logger().get_instance(self)
        cols = line.split(";")

        # TODO: check number of cols
        self.subclass = cols[0]
        # fix SN messing up fully qualified inheritance [class A extends pkg.B {}]
        self.superclass = cols[1].replace(".", "::")
        sourceFile = cols[3]
        start = cols[4].split(".")[0]
        self.sourceLocation = SourceLocation(sourceFile, start, start)
        vis = cols[5].strip()
        self.accessControlQualifier = ""
        self.decomposeVisibility(vis)

        # to be filled in later
        self.package = ""
        self.superSourceLocation = None
コード例 #15
0
    def decomposeData(self):
        # TODO: invEntityLoc - use declLocation or defLocation
        self.sourceFile = self.cols[self.sourceLocationColumnIndex]
        self.start = self.cols[self.sourceLocationColumnIndex +
                               1].split(".")[0]
        self.end = self.start
        srcLoc = SourceLocation(self.sourceFile, self.start, self.end)
        if self.isAnImplementation():
            self.addDefinition(srcLoc)
        else:
            self.addDeclaration(srcLoc)

        i = self.sourceLocationColumnIndex + 3
        declaredType, self.parameters = retrieveSignature(self.cols[i:])
        # deal with inlined method declarations
        declaredType = declaredType.replace("inline ", "")
        typeRef = self.getTypeReference()
        typeRef.setReferencedName(declaredType)
        self.preprocessParameters()
コード例 #16
0
def parseTypedefs(typedefDbLoc, typedefDict, classSelector, namespaceContainmentChecker):
    input_file=open(typedefDbLoc, "r")
    for line in input_file:
        typeDef = TypeDefEntity(line)
        typeDefRef = typeDef.getReference()

        if typeDefRef.isMacroRelatedTypeDef():
            continue

        sourceLoc = typeDefRef.getSourceLocation()
        namespaceName = namespaceContainmentChecker.getSurroundingNamespaceName(sourceLoc)

        typeDefRef.setNamespaceName(namespaceName)

        if typeDefRef.getBaseClass() != None:
            originalTypeWithoutTemplates=typeDefRef.getBaseClass().split("<")[0]

            potentialTargets = classSelector.selectClasses(originalTypeWithoutTemplates, \
                                                        sourceLoc.sourceFile, \
                                                        sourceLoc.start)
            nrOfTargets = len(potentialTargets)

            if ( nrOfTargets > 1 ):
                pass
                #log.warn("TypeDef-base-type-problem: ",nrOfTargets," classes with name \"" + originalTypeWithoutTemplates + ".")
            elif ( nrOfTargets == 0 ):
                pass
                #log.warn("TypeDef-base-type-problem: no class with name \"" + originalTypeWithoutTemplates     + "\" known from file ",sourceLoc.sourceFile,".")
            # Happens regularly, e.g., in case of library classes
            else:
                # get the data on the sole left-over method-owner
                classReference = potentialTargets[0]

                baseSourceLoc = SourceLocation(classReference.getSourceFile(),\
                                                classReference.getLineNr(),\
                                                classReference.getLineNr())
                typeDefRef.setBaseSourceLocation(baseSourceLoc) # note: does not change typeDef

        common.famix.generateTypeDefInfo(typeDefRef)
        typedefDict.add(typeDefRef)
    input_file.close()
コード例 #17
0
def parse(cDb, mtdSrcDict, mtdpfDict, type):
    """ Parse control structure information and write to cdif"""

    ctrlDict = CtrlStructCountDictionary.CtrlStructCountDictionary()
    #mtdpfDict = MethodsPerFileDictionary(mtdSrcDict)

    for line in open(cDb, 'r'):
        splitted = line.split(":")
        srcFile = splitted[0]
        lineNr = int(splitted[1])
        mtd, loc = mtdpfDict.getEnclosing(srcFile, lineNr)
        if mtd:
            ctrlDict.inc(mtd)
        else:
            log.warn("Failed to find owner method of cs: " + srcFile + " " +
                     str(lineNr))

    for mtd, val in ctrlDict.dict.iteritems():
        src = mtdSrcDict.dict[mtd][0].split(":")
        sloc = SourceLocation(src[0], src[1], str(int(src[1]) + 1))
        generateMetrics(type, str(val), mtd, sloc)
コード例 #18
0
def parseVCSMetrics(vcsDb, fileDict):
    """ reads in file change frequency metrics to FAMIX CDIF"""
    timer = Timer("Parsing VCS measurements")
    timer.start()

    nrOfMeasurements = 0
    for line in open(vcsDb, "r"):
        cols = line.split(";")
        fileName = cols[0]
        cf = cols[1].strip()

        #print "VCS", fileName, cf
        if fileName in fileDict.list:
            sLoc = SourceLocation(fileName, "0", "0")
            common.famix.cdifWriter.generateMetrics("CF", cf, fileName, sLoc)
        else:
            log.warn(fileName + " not known to the file dict.")
        nrOfMeasurements += 1

    timer.stop()
    timer.log(nrOfMeasurements)
コード例 #19
0
def parsePmcmetrics(pmcDb, invEntDict):
	from common.metrics  import	PmcMetricEntity
	
	timer = Timer("Parsing measurements")
	timer.start()
	nrOfMeasurements=0
	for line in open(pmcDb, "r"):
		pmcEnt = PmcMetricEntity(line)
		if not pmcEnt.isKnownEntity(invEntDict):
			continue
		
		uniqName = pmcEnt.invEntRef.getUniqueName()
		
		sLoc = SourceLocation(pmcEnt.filename, pmcEnt.lineNr, pmcEnt.lineNr)
		common.famix.cdifWriter.generateMetrics("CC", pmcEnt.metricCC, uniqName, sLoc)
		common.famix.cdifWriter.generateMetrics("NOS", pmcEnt.metricNOS, uniqName, sLoc)
		#common.famix.cdifWriter.generateMetrics("LOC", pmcEnt.metricLOC, uniqName, sLoc)
		common.famix.cdifWriter.generateMetrics("LOC", pmcEnt.metricNOS, uniqName, sLoc)
		nrOfMeasurements += 1

	timer.stop()
	timer.log(nrOfMeasurements)
コード例 #20
0
def parseMethods(dbdumpFile, isImplementation,\
				classSelector, classDict, namespaceContainmentChecker, \
				typedefDict,invokeableEntityDict, methodSourceDict = None):
    nrOfLinesProcessed = 0

    for line in dbdumpFile:
    	
        nrOfLinesProcessed += 1

        isAbstract = False
        method = MethodEntity(isAbstract, isImplementation, line)

        method.postProcessParameters(typedefDict)

        methRef = method.getReference()

        sourceLoc = SourceLocation(methRef.getSourceFile(),\
                                        methRef.getLineNr(),\
                                        methRef.getLineNr())
        namespaceName = namespaceContainmentChecker.getSurroundingNamespaceName(sourceLoc)

        method.setNamespaceName(namespaceName)
        methRef = method.getReference()
		
        parentReference = method.getParentReference()
        potentialTargets = classSelector.selectClasses(parentReference.getReferencedName(),\
                                                 methRef.getSourceFile(), methRef.getLineNr())
        nrOfTargets = len(potentialTargets)

        if ( nrOfTargets > 1 ):
            log.warn("Method-owner-problem: ",nrOfTargets," classes with name \""\
                     + parentReference.getReferencedName() + ".")
            continue # ignore containment link since we can't pinpoint the target.
        elif ( nrOfTargets == 0 ):
        	if parentReference.getCleanName() == "AsamBuilder":
        		references = classDict.getClassesByName(parentReference.getCleanName())

        		assert False

        	log.warn("Method-owner-problem: no class with name \"" \
                    + parentReference.getCleanName() + "\" known from file ",\
                    methRef.getSourceFile(),"@",methRef.getLineNr(),".")
        	# seems to happen for inner-classes, e.g. owner named SpreadsheetApp::Group
        	continue # ignore containment link since we can't find the declaration of the owner.
        else:
            # get the data on the sole left-over method-owner
            classReference = potentialTargets[0]

            parentReference.setSourceFile(classReference.getSourceFile())
            parentReference.setLineNr(classReference.getLineNr())

            # fill in the method owner template parameters
            method.ownerTemplateParameters=classReference.getTemplateParameters()

            if method.ownerTemplateParameters == None:
                method.ownerTemplateParameters=classReference.getTemplateParameters()

            if (methRef.getNamespaceName() == "") and ("::" in methRef.ownerName):
                method.namespaceName = getParentNamespaceName(methRef.ownerName)
                methRef = method.getReference()

        typeReference = method.getTypeReference()

        if not(typeReference.isPrimitive()):
            potentialTargets = classSelector.selectClasses(typeReference.getCleanName(),\
                                                     methRef.getSourceFile(), methRef.getLineNr())
            nrOfTargets = len(potentialTargets)

            if ( nrOfTargets > 1 ):
                pass
                #log.warn("Method-type-problem: ",nrOfTargets," classes with name \""\
                #         + typeReference.getCleanName() + ".")
            elif ( nrOfTargets == 0 ):
                pass
                #log.warn("Method-type-problem: no class with name \"" \
                #        + typeReference.getCleanName() + "\" known from file ",\
                #        methRef.getSourceFile(),"@",methRef.getLineNr(),".")
            else:
                # get the data on the sole left-over method-type
                classReference = potentialTargets[0]

                typeReference.setResolvedName(classReference.getUniqueName())
                typeReference.setSourceFile(classReference.getSourceFile())
                typeReference.setLineNr(classReference.getLineNr())
        else:
            typeReference.setResolvedName(typeReference.getCleanName())

            # TODO: fill in the method type template parameters

        #didNotExistYet = invokeableEntityDictFiller.add(method.getReference())
        invokeableEntityDict.addMultiLocReference(method.getReference())
        if methodSourceDict:
            # this is a definition, add it to methodSrcDict.
            # if you want declarations build another dict
            sLoc = method.getReference().getSourceFile() + ":" + str(method.getReference().getLineNr())
            methodSourceDict.add(method.getReference().getUniqueName(), sLoc)
        invokeableEntityDict.addMultiLocReference(method.getReference())

        #if didNotExistYet:
        #    aCommandList = RuleChecker.checkMethodEntity(method)
        #    RuleChecker.generateMethodInfo(aCommandList, method)

    return nrOfLinesProcessed
コード例 #21
0
def parseFunctions(dbdumpFile, isImpl, typedefDict, namespaceContainmentChecker, classSelector, invokeableEntityDict, methodSourceDict = None):
    nrOfLinesProcessed = 0

    for line in dbdumpFile:
        nrOfLinesProcessed += 1
        line = line.strip()

        function = FunctionEntity(isImpl, line)
        function.postProcessParameters(typedefDict)

        functionRef = function.getReference()
        sourceLoc = SourceLocation(functionRef.getSourceFile(),\
                                        functionRef.getLineNr(),\
                                        functionRef.getLineNr())

        namespaceName = namespaceContainmentChecker.getSurroundingNamespaceName(sourceLoc)
        function.namespaceName = namespaceName

        functionRef = function.getReference()

        typeReference = function.getTypeReference()

        if not(typeReference.isPrimitive()):
            potentialTargets = classSelector.selectClasses(typeReference.getCleanName(),\
                                                     functionRef.getSourceFile(), functionRef.getLineNr())
            nrOfTargets = len(potentialTargets)

            if ( nrOfTargets > 1 ):
                pass
                #log.warn("Function-type-problem: ",nrOfTargets," classes with name \""\
                #         + typeReference.getCleanName() + ".")
            elif ( nrOfTargets == 0 ):
                pass
                #log.warn("Function-type-problem: no class with name \"" \
                #        + typeReference.getCleanName() + "\" known from file ",\
                #        functionRef.getSourceFile(),"@",functionRef.getLineNr(),".")
            else:
                # get the data on the sole left-over method-type
                classReference = potentialTargets[0]

                typeReference.setResolvedName(classReference.getUniqueName())
                typeReference.setSourceFile(classReference.getSourceFile())
                typeReference.setLineNr(classReference.getLineNr())

                # TODO: fill in the return type template parameters
        else:
            typeReference.setResolvedName(typeReference.getCleanName())

        if methodSourceDict:
            # this is a definition, add it to methodSrcDict.
            # if you want declarations build another di        if methodSourceDict:
            # this is a definition, add it to methodSrcDict.
            # if you want declarations build another dict
            sLoc = functionRef.getSourceFile() + ":" + str(functionRef.getLineNr())
            methodSourceDict.add(functionRef.getUniqueName(), sLoc)

            sLoc = functionRef.getSourceFile() + ":" + str(functionRef.getLineNr())
            methodSourceDict.add(functionRef.getUniqueName(), sLoc)

        invokeableEntityDict.addMultiLocReference(functionRef)

    return nrOfLinesProcessed
コード例 #22
0
    def selectClasses(self, qualifiedClassName, referencingSourceFile,
                      referencingLineNr):
        relevantClassReferences = []

        translatedName = self.translateAsTypeDef(qualifiedClassName)

        parentNamespaceName = getParentNamespaceName(qualifiedClassName)
        nonQualifiedClassName = getNonQualifiedName(qualifiedClassName)

        #namespacesUsed = self.scope.getUsedNamespaces(parentNamespaceName, referencingSourceFile, referencingLineNr)
        namespacesUsed = self.scope.getUsedNamespaces(referencingSourceFile,
                                                      referencingLineNr)

        if parentNamespaceName != "":
            index = 0
            while index < len(namespacesUsed):
                usedNamespace = namespacesUsed[index]
                if usedNamespace == "":
                    usedNamespace = parentNamespaceName
                else:
                    usedNamespace += "::" + parentNamespaceName
                namespacesUsed[index] = usedNamespace
                index += 1

        classReferences = self.classCollector.collectClassReferences(
            nonQualifiedClassName, namespacesUsed)

        # Which classes are reachable through (transitive) #includes?
        #print qualifiedClassName
        transIncludeDict = self.scope.getTransitiveIncludeDict()
        transitiveIncludedFiles = transIncludeDict.getTransitiveIncludedFiles(
            referencingSourceFile)
        for classReference in classReferences:
            sourceFile = classReference.getSourceFile()
            #print sourceFile, " in ", transitiveIncludedFiles
            #selectSourceFileMatches(sourceFile,transitiveIncludedFiles)
            if sourceFile in transitiveIncludedFiles:
                if not (classReference in relevantClassReferences):
                    relevantClassReferences.append(classReference)
            else:
                conf = transIncludeDict.trySymlinkPath(
                    sourceFile, transitiveIncludedFiles)
                if conf > 1 and not (classReference
                                     in relevantClassReferences):
                    relevantClassReferences.append(classReference)

        sl = SourceLocation(referencingSourceFile, referencingLineNr,
                            referencingLineNr)

        # TODO: we do an 'or' here, but we should check that (i) it is reachable
        # via include, and (ii) the namespacing is also ok

        # Which classes are reachable through namespacing.
        usedClassesLocations = self.scope.getTransitiveUsedClassesLocationsUsingLoc(
            sl)
        for usedClassLoc in usedClassesLocations:
            # convert to ClassReferenceEntity
            clsName = usedClassLoc.getNonQualifiedName()
            nspName = utils.spliceLastPackageName(usedClassLoc.getName(),
                                                  utils.qualSeparator)
            sLoc = usedClassLoc.getSourceLocations()[0]

            cre = ClassReferenceEntity(clsName, nspName, sLoc.sourceFile,
                                       sLoc.start, "")
            if clsName == qualifiedClassName and not cre in relevantClassReferences:
                relevantClassReferences.append(cre)

        return relevantClassReferences
コード例 #23
0
def parseAttributes(attributeDBD, classSelector, attributeDictFiller, namespaceContainmentChecker):

    for line in open(attributeDBD, 'r'):
        attribute = AttributeEntity(line)
        attrRef = attribute.getReference()

        sourceLoc = SourceLocation(attrRef.getSourceFile(),\
                                        attrRef.getLineNr(),\
                                        attrRef.getLineNr())
        namespaceName = namespaceContainmentChecker.getSurroundingNamespaceName(sourceLoc)

        attribute.setNamespaceName(namespaceName)
        attrRef = attribute.getReference()

        parentRef = attribute.getParentReference()
        potentialTargets = classSelector.selectClasses(parentRef.getReferencedName(), attrRef.getSourceFile(), attrRef.getLineNr())
        nrOfTargets = len(potentialTargets)

        if ( nrOfTargets > 1 ):
            log.warn("Attribute-owner-problem: ",nrOfTargets," classes with name \"" + parentRef.getReferencedName() + ".")
            continue # ignore containment link since we can't pinpoint the target.
        elif ( nrOfTargets == 0 ):
            log.warn("Attribute-owner-problem: no class with name \"" + parentRef.getReferencedName() + "\" known from file ",attrRef.getSourceFile(),"@",attrRef.getLineNr(),".")
            # seems to happen for inner-classes, e.g. owner named SpreadsheetApp::Group
            continue # ignore containment link since we can't find the declaration of the owner.
        else:
            # get the data on the sole left-over attribute-owner
            classReference = potentialTargets[0]
            parentRef.setSourceFile(classReference.getSourceFile())
            parentRef.setLineNr(classReference.getLineNr())
            attribute.ownerTemplateParameters=classReference.getTemplateParameters()

        # resolve the attribute type
        typeRef = attribute.getTypeReference()

        if not(typeRef.isPrimitive()):
            potentialTargets = classSelector.selectClasses(typeRef.getCleanName(),\
                                                     attrRef.getSourceFile(), attrRef.getLineNr())
            nrOfTargets = len(potentialTargets)

            if ( nrOfTargets > 1 ):
                pass
                #log.warn("Attribute-type-problem: ",nrOfTargets," classes with name \""\
                #         + typeRef.getCleanName() + ".")
                typeRef.setResolvedName(typeRef.getCleanName())
            elif ( nrOfTargets == 0 ):
                pass
                #log.warn("Attribute-type-problem: no class with name \"" \
                #        + typeRef.getCleanName() + "\" known from file ",\
                #        attrRef.getSourceFile(),"@",attrRef.getLineNr(),".")
                typeRef.setResolvedName(typeRef.getCleanName())
            else:
                # get the data on the sole left-over method-type
                classReference = potentialTargets[0]

                typeRef.setResolvedName(classReference.getUniqueName())
                typeRef.setSourceFile(classReference.getSourceFile())
                typeRef.setLineNr(classReference.getLineNr())

                # TODO: fill in the attribute type template parameters
        else:
            typeRef.setResolvedName(typeRef.getCleanName())
        
        attrRef = attribute.getReference()

        # TODO: also put the attribute type in the attribute dictionary, so that it can be passed
        # on to the access-dictionary when accesses are resolved. That way, the resolution of
        # further accesses invocations

        aCommandList = RuleChecker.checkAttributeEntity(attribute)
        RuleChecker.generateAttributeInfo(aCommandList, attribute)
        attributeDictFiller.add(attribute)
コード例 #24
0
	def getSourceLocation(self):
		return SourceLocation(self.includingFile, self.includeLineNr, \
							self.includeLineNr)
コード例 #25
0
ファイル: javaEntities.py プロジェクト: carvalhomb/tsmells
    def determineSourceLocation(self):
        sourceFile = self.cols[2]
        start = self.cols[3].split(".")[0]

        self.sourceLocation = SourceLocation(sourceFile, start, start)