bad_smell_listener.go 12.9 KB
Newer Older
P
Phodal Huang 已提交
1 2 3
package bs

import (
4
	"github.com/antlr/antlr4/runtime/Go/antlr"
P
Phodal Huang 已提交
5
	"github.com/phodal/coca/core/domain/bs_domain"
P
Phodal Huang 已提交
6
	. "github.com/phodal/coca/languages/java"
P
Phodal Huang 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19
	"reflect"
	"strings"
)

var imports []string
var clzs []string
var currentPkg string
var currentClz string
var currentClzType string

var currentClzExtends string
var currentClzImplements []string

P
Phodal Huang 已提交
20 21
var methods []bs_domain.BsJMethod
var methodCalls []bs_domain.BsJMethodCall
P
Phodal Huang 已提交
22 23 24 25

var fields = make(map[string]string)
var localVars = make(map[string]string)
var formalParameters = make(map[string]string)
P
Phodal Huang 已提交
26
var currentClassBs bs_domain.ClassBadSmellInfo
P
Phodal Huang 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

func NewBadSmellListener() *BadSmellListener {
	currentClz = ""
	currentPkg = ""
	methods = nil
	methodCalls = nil
	currentClzImplements = nil
	currentClzExtends = ""
	return &BadSmellListener{}
}

type BadSmellListener struct {
	BaseJavaParserListener
}

P
Phodal Huang 已提交
42 43
func (s *BadSmellListener) getNodeInfo() bs_domain.BsJClass {
	return *&bs_domain.BsJClass{
P
Phodal Huang 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
		currentPkg,
		currentClz,
		currentClzType,
		"",
		currentClzExtends,
		currentClzImplements,
		methods,
		methodCalls,
		currentClassBs,
	}
}

func (s *BadSmellListener) EnterPackageDeclaration(ctx *PackageDeclarationContext) {
	currentPkg = ctx.QualifiedName().GetText()
}

func (s *BadSmellListener) EnterImportDeclaration(ctx *ImportDeclarationContext) {
	importText := ctx.QualifiedName().GetText()
	imports = append(imports, importText)
}

func (s *BadSmellListener) EnterClassDeclaration(ctx *ClassDeclarationContext) {
	currentClzType = "Class"
	currentClz = ctx.IDENTIFIER().GetText()

	if ctx.EXTENDS() != nil {
		currentClzExtends = ctx.TypeType().GetText()
	}

	if ctx.IMPLEMENTS() != nil {
		typeList := ctx.TypeList().(*TypeListContext)
		for _, typ := range typeList.AllTypeType() {
			typeData := getTypeDATA(typ.(*TypeTypeContext))
			currentClzImplements = append(currentClzImplements, typeData)
		}
	}
}

func getTypeDATA(typ *TypeTypeContext) string {
	var typeData string
	classOrInterface := typ.ClassOrInterfaceType().(*ClassOrInterfaceTypeContext)
	if classOrInterface != nil {
		identifiers := classOrInterface.AllIDENTIFIER()
		typeData = identifiers[len(identifiers)-1].GetText()
	}

	return typeData
}

func (s *BadSmellListener) EnterInterfaceDeclaration(ctx *InterfaceDeclarationContext) {
	currentClzType = "Interface"
	currentClz = ctx.IDENTIFIER().GetText()
}

func (s *BadSmellListener) EnterInterfaceMethodDeclaration(ctx *InterfaceMethodDeclarationContext) {
	startLine := ctx.GetStart().GetLine()
	startLinePosition := ctx.IDENTIFIER().GetSymbol().GetColumn()
	stopLine := ctx.GetStop().GetLine()
	name := ctx.IDENTIFIER().GetText()
	stopLinePosition := startLinePosition + len(name)
	methodBody := ctx.MethodBody().GetText()

106 107 108 109 110
	var modifiers = ""
	allModifier := ctx.AllInterfaceMethodModifier()
	methodModifierLen := len(allModifier)
	for index, modifier := range allModifier {
		modifiers = modifiers + modifier.GetText()
P
Phodal Huang 已提交
111
		if index < methodModifierLen-1 {
112 113 114 115
			modifiers = modifiers + ","
		}
	}

P
Phodal Huang 已提交
116 117
	typeType := ctx.TypeTypeOrVoid().GetText()

P
Phodal Huang 已提交
118
	var methodParams []bs_domain.JFullParameter = nil
P
Phodal Huang 已提交
119 120 121 122 123 124 125 126 127
	parameters := ctx.FormalParameters()
	if parameters != nil {
		if reflect.TypeOf(parameters.GetChild(1)).String() == "*parser.FormalParameterListContext" {
			allFormal := parameters.GetChild(1).(*FormalParameterListContext)
			formalParameter := allFormal.AllFormalParameter()
			for _, param := range formalParameter {
				paramContext := param.(*FormalParameterContext)
				paramType := paramContext.TypeType().GetText()
				paramValue := paramContext.VariableDeclaratorId().(*VariableDeclaratorIdContext).IDENTIFIER().GetText()
P
Phodal Huang 已提交
128
				methodParams = append(methodParams, *&bs_domain.JFullParameter{paramType, paramValue})
P
Phodal Huang 已提交
129 130 131 132
			}
		}
	}

P
Phodal Huang 已提交
133
	methodBSInfo := bs_domain.NewMethodBadSmellInfo()
P
Phodal Huang 已提交
134

P
Phodal Huang 已提交
135
	method := &bs_domain.BsJMethod{
136 137 138 139 140 141 142 143 144 145
		Name:              name,
		Type:              typeType,
		StartLine:         startLine,
		StartLinePosition: startLinePosition,
		StopLine:          stopLine,
		StopLinePosition:  stopLinePosition,
		MethodBody:        methodBody,
		Modifier:          modifiers,
		Parameters:        methodParams,
		MethodBs:          methodBSInfo,
P
Phodal Huang 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
	}

	methods = append(methods, *method)
}

func (s *BadSmellListener) EnterFormalParameter(ctx *FormalParameterContext) {
	formalParameters[ctx.VariableDeclaratorId().GetText()] = ctx.TypeType().GetText()
}

func (s *BadSmellListener) EnterFieldDeclaration(ctx *FieldDeclarationContext) {
	declarators := ctx.VariableDeclarators()
	variableName := declarators.GetParent().GetChild(0).(antlr.ParseTree).GetText()

	for _, declarator := range declarators.(*VariableDeclaratorsContext).AllVariableDeclarator() {
		value := declarator.(*VariableDeclaratorContext).VariableDeclaratorId().(*VariableDeclaratorIdContext).IDENTIFIER().GetText()
		fields[value] = variableName
	}
}

func (s *BadSmellListener) EnterLocalVariableDeclaration(ctx *LocalVariableDeclarationContext) {
	typ := ctx.GetChild(0).(antlr.ParseTree).GetText()
	variableName := ctx.GetChild(1).GetChild(0).GetChild(0).(antlr.ParseTree).GetText()
	localVars[variableName] = typ
}

func (s *BadSmellListener) EnterMethodDeclaration(ctx *MethodDeclarationContext) {
	startLine := ctx.GetStart().GetLine()
	startLinePosition := ctx.IDENTIFIER().GetSymbol().GetColumn()
	stopLine := ctx.GetStop().GetLine()
	name := ctx.IDENTIFIER().GetText()
	stopLinePosition := startLinePosition + len(name)
P
Phodal Huang 已提交
177 178

	modifier := getModifier(ctx)
P
Phodal Huang 已提交
179 180 181 182

	typeType := ctx.TypeTypeOrVoid().GetText()
	methodBody := ctx.MethodBody().GetText()

P
Phodal Huang 已提交
183
	var methodParams []bs_domain.JFullParameter = nil
P
Phodal Huang 已提交
184 185 186 187 188 189 190 191 192
	parameters := ctx.FormalParameters()
	if parameters != nil {
		if reflect.TypeOf(parameters.GetChild(1)).String() == "*parser.FormalParameterListContext" {
			allFormal := parameters.GetChild(1).(*FormalParameterListContext)
			formalParameter := allFormal.AllFormalParameter()
			for _, param := range formalParameter {
				paramContext := param.(*FormalParameterContext)
				paramType := paramContext.TypeType().GetText()
				paramValue := paramContext.VariableDeclaratorId().(*VariableDeclaratorIdContext).IDENTIFIER().GetText()
P
Phodal Huang 已提交
193
				methodParams = append(methodParams, bs_domain.JFullParameter{paramType, paramValue})
P
Phodal Huang 已提交
194 195 196 197 198 199

				localVars[paramValue] = paramType
			}
		}
	}

P
Phodal Huang 已提交
200
	methodBSInfo := bs_domain.NewMethodBadSmellInfo()
P
Phodal Huang 已提交
201 202
	methodBadSmellInfo := buildMethodBSInfo(ctx, methodBSInfo)

P
Phodal Huang 已提交
203
	method := &bs_domain.BsJMethod{
204 205 206 207 208 209 210
		Name:              name,
		Type:              typeType,
		StartLine:         startLine,
		StartLinePosition: startLinePosition,
		StopLine:          stopLine,
		StopLinePosition:  stopLinePosition,
		MethodBody:        methodBody,
P
Phodal Huang 已提交
211
		Modifier:          modifier,
212 213
		Parameters:        methodParams,
		MethodBs:          methodBadSmellInfo,
P
Phodal Huang 已提交
214 215 216 217
	}
	methods = append(methods, *method)
}

P
Phodal Huang 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
func getModifier(ctx *MethodDeclarationContext) string {
	var modifier = ""
	if reflect.TypeOf(ctx.GetParent()).String() == "*parser.MemberDeclarationContext" {
		firstChild := ctx.GetParent().(*MemberDeclarationContext).GetParent().GetChild(0)
		if reflect.TypeOf(firstChild).String() == "*parser.ModifierContext" {
			modifierCtx := firstChild.(*ModifierContext)
			if reflect.TypeOf(modifierCtx.GetChild(0)).String() == "*parser.ClassOrInterfaceModifierContext" {
				context := modifierCtx.GetChild(0).(*ClassOrInterfaceModifierContext)
				modifier = context.GetText()
			}
		}
	}
	return modifier
}

P
Phodal Huang 已提交
233
func buildMethodBSInfo(context *MethodDeclarationContext, bsInfo bs_domain.MethodBadSmellInfo) bs_domain.MethodBadSmellInfo {
P
Phodal Huang 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246
	methodBody := context.MethodBody()
	blockContext := methodBody.GetChild(0)
	if reflect.TypeOf(blockContext).String() == "*parser.BlockContext" {
		blcStatement := blockContext.(*BlockContext).AllBlockStatement()
		for _, statement := range blcStatement {
			if reflect.TypeOf(statement.GetChild(0)).String() == "*parser.StatementContext" {
				if len(statement.GetChild(0).(*StatementContext).GetChildren()) < 3 {
					continue
				}

				statementCtx := statement.GetChild(0).(*StatementContext)
				if (reflect.TypeOf(statementCtx.GetChild(1)).String()) == "*parser.ParExpressionContext" {
					if statementCtx.GetChild(0).(antlr.ParseTree).GetText() == "if" {
247 248 249 250 251
						if reflect.TypeOf(statementCtx.GetChild(1)).String() == "*parser.ParExpressionContext" {
							parCtx := statementCtx.GetChild(1).(*ParExpressionContext)
							startLine := parCtx.GetStart().GetLine()
							endLine := parCtx.GetStop().GetLine()

P
Phodal Huang 已提交
252
							info := bs_domain.NewIfPairInfo()
253 254 255 256 257
							info.StartLine = startLine
							info.EndLine = endLine
							bsInfo.IfInfo = append(bsInfo.IfInfo, info)
						}

P
Phodal Huang 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
						bsInfo.IfSize = bsInfo.IfSize + 1
					}

					if statementCtx.GetChild(0).(antlr.ParseTree).GetText() == "switch" {
						bsInfo.SwitchSize = bsInfo.SwitchSize + 1
					}

				}
			}
		}
	}

	return bsInfo
}

func (s *BadSmellListener) EnterFormalParameterList(ctx *FormalParameterListContext) {
	//fmt.Println(ctx.GetParent().GetParent().(antlr.RuleNode).get)
	//fmt.Println(ctx.AllFormalParameter()
}

func (s *BadSmellListener) EnterAnnotation(ctx *AnnotationContext) {
	if currentClzType == "Class" && ctx.QualifiedName().GetText() == "Override" {
		currentClassBs.OverrideSize++
	}
}

func (s *BadSmellListener) EnterCreator(ctx *CreatorContext) {
	variableName := ctx.GetParent().GetParent().GetChild(0).(antlr.ParseTree).GetText()
	localVars[variableName] = ctx.CreatedName().GetText()
}

func (s *BadSmellListener) EnterLocalTypeDeclaration(ctx *LocalTypeDeclarationContext) {

}

func (s *BadSmellListener) EnterMethodCall(ctx *MethodCallContext) {
	var targetCtx = ctx.GetParent().GetChild(0).(antlr.ParseTree).GetText()
	var targetType = parseTargetType(targetCtx)
	callee := ctx.GetChild(0).(antlr.ParseTree).GetText()

	startLine := ctx.GetStart().GetLine()
	startLinePosition := ctx.GetStart().GetColumn()
	stopLine := ctx.GetStop().GetLine()
	stopLinePosition := startLinePosition + len(callee)

	//typeType := ctx.GetChild(0).(antlr.ParseTree).TypeTypeOrVoid().GetText()

	// TODO: 处理链试调用
	if strings.Contains(targetType, "()") && strings.Contains(targetType, ".") {
		split := strings.Split(targetType, ".")
		sourceTarget := split[0]
		targetType = localVars[sourceTarget]
	}

	fullType := warpTargetFullType(targetType)
	if targetType == "super" {
		targetType = currentClzExtends
	}
	if fullType != "" {
P
Phodal Huang 已提交
317
		jMethodCall := *&bs_domain.BsJMethodCall{removeTarget(fullType), "", targetType, callee, startLine, startLinePosition, stopLine, stopLinePosition}
P
Phodal Huang 已提交
318
		methodCalls = append(methodCalls, jMethodCall)
P
Phodal Huang 已提交
319 320
	} else {
		if ctx.GetText() == targetType {
P
Phodal Huang 已提交
321
			jMethodCall := *&bs_domain.BsJMethodCall{currentPkg, "", currentClz, callee, startLine, startLinePosition, stopLine, stopLinePosition}
P
Phodal Huang 已提交
322
			methodCalls = append(methodCalls, jMethodCall)
P
Phodal Huang 已提交
323
		} else {
P
Phodal Huang 已提交
324
			jMethodCall := *&bs_domain.BsJMethodCall{currentPkg, "NEEDFIX", targetType, callee, startLine, startLinePosition, stopLine, stopLinePosition}
P
Phodal Huang 已提交
325
			methodCalls = append(methodCalls, jMethodCall)
P
Phodal Huang 已提交
326 327 328 329 330 331
		}
	}
}

func (s *BadSmellListener) EnterExpression(ctx *ExpressionContext) {
	// lambda BlogPO::of
P
Phodal Huang 已提交
332
	if ctx.COLONCOLON() != nil && ctx.Expression(0) != nil {
P
Phodal Huang 已提交
333 334 335 336 337 338 339 340 341 342
		text := ctx.Expression(0).GetText()
		methodName := ctx.IDENTIFIER().GetText()
		targetType := parseTargetType(text)
		fullType := warpTargetFullType(targetType)

		startLine := ctx.GetStart().GetLine()
		startLinePosition := ctx.GetStart().GetColumn()
		stopLine := ctx.GetStop().GetLine()
		stopLinePosition := startLinePosition + len(text)

P
Phodal Huang 已提交
343
		jMethodCall := &bs_domain.BsJMethodCall{removeTarget(fullType), "", targetType, methodName, startLine, startLinePosition, stopLine, stopLinePosition}
P
Phodal Huang 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
		methodCalls = append(methodCalls, *jMethodCall)
	}
}

func (s *BadSmellListener) appendClasses(classes []string) {
	clzs = classes
}

func removeTarget(fullType string) string {
	split := strings.Split(fullType, ".")
	return strings.Join(split[:len(split)-1], ".")
}

func parseTargetType(targetCtx string) string {
	targetVar := targetCtx
	targetType := targetVar

	//TODO: update this reflect
	typeOf := reflect.TypeOf(targetCtx).String()
	if strings.HasSuffix(typeOf, "MethodCallContext") {
364
		targetType = currentClz
P
Phodal Huang 已提交
365 366 367 368 369 370 371
	} else {
		fieldType := fields[targetVar]
		formalType := formalParameters[targetVar]
		localVarType := localVars[targetVar]
		if fieldType != "" {
			targetType = fieldType
		} else if formalType != "" {
372
			targetType = formalType
P
Phodal Huang 已提交
373
		} else if localVarType != "" {
374
			targetType = localVarType
P
Phodal Huang 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
		}
	}

	return targetType
}

func warpTargetFullType(targetType string) string {
	if strings.EqualFold(currentClz, targetType) {
		return currentPkg + "." + targetType
	}

	// TODO: update for array
	split := strings.Split(targetType, ".")
	str := split[0]
	pureTargetType := strings.ReplaceAll(strings.ReplaceAll(str, "[", ""), "]", "")

	for index := range imports {
		imp := imports[index]
		if strings.HasSuffix(imp, pureTargetType) {
			return imp
		}
	}

	//maybe the same package
	for _, clz := range clzs {
		if strings.HasSuffix(clz, "."+pureTargetType) {
			return clz
		}
	}

	//1. current package, 2. import by *
	if pureTargetType == "super" {
		for index := range imports {
			imp := imports[index]
			if strings.HasSuffix(imp, currentClzExtends) {
				return imp
			}
		}
	}

	return ""
}