/// <summary> /// add the callee Edge /// </summary> /// <param name="m_caller"></param> /// <param name="m_callee"></param> /// <returns> true if this set did not already contain the specified element </returns> public bool AddCalleeEdge(MethodDefinition m_caller, MethodDefinition m_callee) { int colPos = index[m_caller]; // index for the caller in the CallGraph int linkedNodePos = index[m_callee]; // index for the callee in the CallGraph HashSet<int> hs = _calleeEdge[colPos]; // get caller's _calleeEdge set return hs.Add(linkedNodePos); // add the index of m's callee }
/// <summary> /// Construct the method summarizer /// </summary> /// <param name="md"></param> public SwumSummary(MethodDefinition md) { this.Method = md; var classBelong = md.GetAncestors<TypeDefinition>().FirstOrDefault(); //class name if (classBelong != null) { ClassName = classBelong.Name; } else { ClassName = ""; } //return type string returnType = "void"; if (md.ReturnType != null) { returnType = md.ReturnType.ToString(); } //Check if md returns primitive bool IsPrimitive = IsPrimitiveType(md.ReturnType); HashSet<FormalParameterRecord> paras = new HashSet<FormalParameterRecord>(); foreach (var para in md.Parameters) { var vType = para.VariableType; var tempPara = new FormalParameterRecord(vType.ToString(), BuiltInTypeFactory.IsBuiltIn(vType), para.Name); paras.Add(tempPara); } MethodContext mc = new MethodContext(returnType, IsPrimitive, ClassName, paras, false, md.IsConstructor, md.IsDestructor); this._mDeclarationNode = new MethodDeclarationNode(md.Name, mc); this._builder = new UnigramSwumBuilder(); this.IsSummarized = false; }
/// <summary> /// add the callee Edge /// </summary> /// <param name="m_caller"></param> /// <param name="m_callee"></param> /// <returns> true if this set did not already contain the specified element </returns> public bool AddCallerEdge(MethodDefinition m_caller, MethodDefinition m_callee) { int colPos = index[m_callee]; int linkedNodePos = index[m_caller]; HashSet<int> hs = _callerEdge[colPos]; return hs.Add(linkedNodePos); }
/// <summary> /// Determines whether the specified caller contains relationship. /// </summary> /// <param name="caller">The caller.</param> /// <param name="callee">The callee.</param> /// <returns> /// <c>true</c> if the specified caller contains relationship; otherwise, <c>false</c>. /// </returns> public bool ContainsRelationship(MethodDefinition caller, MethodDefinition callee) { if (null == caller) throw new ArgumentNullException("caller"); if (null == callee) throw new ArgumentNullException("callee"); return ContainsRelationship(caller.MethodSignature, callee.MethodSignature); }
/// <summary> /// Copy constructor /// </summary> /// <param name="otherDefinition">The scope to copy from</param> public MethodDefinition(MethodDefinition otherDefinition) : base(otherDefinition) { IsConstructor = otherDefinition.IsConstructor; IsDestructor = otherDefinition.IsDestructor; _parameters = new List<ParameterDeclaration>(); Parameters = new ReadOnlyCollection<ParameterDeclaration>(_parameters); AddMethodParameters(otherDefinition.Parameters); }
public desMethod(MethodDefinition m, string sum, List<MethodDefinition> followers, List<MethodDefinition> finals) { this.swumsummary = TakeSpaceOff(sum); this.methodself = m; this.name = m.GetFullName(); this.followmethods = followers; this.finalmethods = finals; this.sqlStmts = new List<sqlStmtParser>(); }
public Method(MethodDefinition methodDef) { FilePath = methodDef.PrimaryLocation.SourceFileName; NameSpace = methodDef.GetFullName(); //the global level of namespace is the file name Type = methodDef.GetAncestors<TypeDefinition>().FirstOrDefault().Name; Name = methodDef.Name; StartLineNumber = methodDef.PrimaryLocation.StartingLineNumber; SetParameterNames(methodDef); SetParameterTypes(methodDef); }
/// <summary> /// find all callee paths from m to all its reachable paths (bounded by a constant) /// </summary> /// <param name="m"></param> /// <returns></returns> public List<List<MethodDefinition>> FindCalleeList(MethodDefinition m) { _calleeList = new List<List<MethodDefinition>>(); if (!cg.ContainsMethod(m)) { return _calleeList; } List<MethodDefinition> path = new List<MethodDefinition>(); FindCalleeListHelper(m, new List<MethodDefinition>(path), 0); return _calleeList; }
private static bool Verify(SrcMLDataContext db, MethodDefinition def, XElement use) { var methodNameElement = SrcMLHelper.GetNameForMethod(use); bool namesMatch = def.MethodName == methodNameElement.Value; var numberOfArguments = use.Element(SRC.ArgumentList).Elements(SRC.Argument).Count(); var mininumNumberOfArguments = def.NumberOfMethodParameters - def.NumberOfMethodParametersWithDefaults; bool argCountMatches = numberOfArguments >= mininumNumberOfArguments && numberOfArguments <= def.NumberOfMethodParameters; return namesMatch && argCountMatches; }
/// <summary> /// add a node to the graph /// </summary> /// <param name="m"></param> /// <returns></returns> public bool AddNode(MethodDefinition m) { if (!index.ContainsKey(m)) { this.nodes.Add(m); this.index[m] = size++; this._calleeEdge.Add(new HashSet<int>()); this._callerEdge.Add(new HashSet<int>()); return true; } else { return false; } }
public MethodDefinition(SrcMLArchive archive, MethodData data, MethodCall fromCall) { this.Archive = archive; this.SourceCall = fromCall; this.Data = data; this.isValid = false; this.Location = data.PrimaryLocation; this.FullName = Data.GetFullName(); this.Id = DataHelpers.GetLocation(Location); this.Path = Location.SourceFileName; this.Signature = GetMethodSignature(); }
/// <summary> /// Init the method analyzer and analyze the method automatically /// </summary> /// <param name="method"></param> public MethodAnalyzer(MethodDefinition method) { Method = method; ParametersInfo = new HashSet<VariableInfo>(); VariablesInfo = new HashSet<VariableInfo>(); SetSelfFields = new HashSet<VariableDeclaration>(); GetSelfFields = new HashSet<VariableDeclaration>(); PropertyFields = new HashSet<VariableDeclaration>(); InvokedExternalMethods = new HashSet<MethodDefinition>(); InvokedLocalMethods = new HashSet<MethodDefinition>(); IsReturnNewObj = false; IsSuccess = 0; IsSuccess = Analyze(); }
/// <summary> /// Gets all of the method calls in this statement that matches <paramref name="otherMethod"/> /// </summary> /// <param name="root">The statement to start searching from</param> /// <param name="otherMethod">The other method</param> /// <param name="searchDescendantStatements">If true, this will return all the method calls to<paramref name="otherMethod"/> from <paramref name="root"/> and its descendants</param> public static IEnumerable<MethodCall> GetCallsTo(this Statement root, MethodDefinition otherMethod, bool searchDescendantStatements) { if(null == otherMethod) { throw new ArgumentNullException("otherMethod"); } //first filter calls for ones with the same name, number of parameters, etc. var initialMatches = root.FindExpressions<MethodCall>(searchDescendantStatements).Where(c => c.SignatureMatches(otherMethod)).ToList(); if(initialMatches.Any()) { //check whether the call actually resolves to the other method foreach(var call in initialMatches) { if(call.FindMatches().Any(m => m == otherMethod)) { yield return call; } } } }
public MethodDefinition(SrcMLArchive archive, MethodData data, MethodCall fromCall) { this.Archive = archive; this.SourceCall = fromCall; this.Data = data; this.isValid = false; this.Location = data.PrimaryLocation; this.FullName = Data.GetFullName(); this.Id = DataHelpers.GetLocation(Location); this.Path = Location.SourceFileName; this.Signature = GetMethodSignature(); }
//This method is used to find all the statement related the the statement "declcont". public void FindRelated(MethodDefinition m, VariableDeclaration declcont, List<string[]> variables) { foreach (var stat in m.GetDescendants<Statement>()) { if (stat is DeclarationStatement || stat is SwitchStatement || stat is ABB.SrcML.Data.ThrowStatement || stat is ABB.SrcML.Data.ReturnStatement) continue; if (stat.Content == null) continue; IEnumerable<Expression> exps = stat.Content.GetDescendants(); if (exps.Count<Expression>() <= 1) continue; var firstexp = exps.First<Expression>(); if ((firstexp.ToString() != declcont.Name) || !(firstexp is NameUse)) continue; if (!(exps.ElementAt(1) is OperatorUse)) continue; OperatorUse opt = (OperatorUse)exps.ElementAt(1); string targetstring = Rebuildstring(declcont.Name, stat, variables); if (opt.Text == "+=") { UpdateVariable(declcont.Name, variables, GetVariableCont(declcont.Name, variables) + targetstring); } if (opt.Text == "=") { UpdateVariable(declcont.Name, variables, targetstring); } } }
/// <summary> /// add a node to the graph /// </summary> /// <param name="m"></param> /// <returns></returns> public bool AddNode(MethodDefinition m) { if (!index.ContainsKey(m)) { this.nodes.Add(m); this.index[m] = size++; // add the calleeEdge and the callerEdge for this newly added method // _calleeEdge[index[m]] --> m's calleeEdge // _callerEdge[index[m]] --> m's callerEdge this._calleeEdge.Add(new HashSet<int>()); this._callerEdge.Add(new HashSet<int>()); return true; } else { return false; } }
/// <summary> /// Check if the given method is a SQL Operating method, /// that is get/set/constructor defined in a POJO class /// </summary> /// <param name="method"></param> /// <param name="allDBClassToTableName"></param> /// <param name="allDBClassPropToTableAttr"></param> /// <returns>Return null if not SQL Operating method.</returns> public static BasicMethod CheckIfGetSetMethodsInPOJOClass(MethodDefinition method, Dictionary<string, string> allDBClassToTableName, Dictionary<string, string> allDBClassPropToTableAttr) { BasicMethod basictMethod = null; string methodFullName = method.GetFullName(); string curClassName = ""; TypeDefinition declaringClass = MethodUtil.GetDeclaringClass(method); if (declaringClass == null) { return basictMethod; } else { curClassName = declaringClass.GetFullName(); } //Console.WriteLine(curClassName); if (!allDBClassToTableName.ContainsKey(curClassName)) // if not from POJO class return; { return basictMethod; } HibernateMethodAnalyzer mAnalyzer = new HibernateMethodAnalyzer(method); if (mAnalyzer.IsSuccess != 0) { //Console.WriteLine(mAnalyzer.GetFailInfo()); return basictMethod; } string tableName = allDBClassToTableName[curClassName]; // (1) handle Basic POJO DB Class Constructors if (method.IsConstructor) { HashSet<string> attrList = new HashSet<string>(); foreach (VariableDeclaration vd in mAnalyzer.SetSelfFields) { string fullClassPropName = curClassName + "." + vd.Name; if (allDBClassPropToTableAttr.ContainsKey(fullClassPropName)) { string[] temps = allDBClassPropToTableAttr[fullClassPropName].Split('.'); attrList.Add(temps[1]); } } basictMethod = new BasicMethod(Constants.BasicMethodType.Construct, tableName, attrList); } else // (2) handle Basic POJO DB Class Get/Set methods { HashSet<VariableDeclaration> getSelfFiels = mAnalyzer.GetSelfFields; HashSet<VariableDeclaration> setSelfFiels = mAnalyzer.SetSelfFields; if (getSelfFiels.Count() == 1 && setSelfFiels.Count() == 0) { VariableDeclaration para = getSelfFiels.SingleOrDefault(); string fullClassPropName = curClassName + "." + para.Name; if (allDBClassPropToTableAttr.ContainsKey(fullClassPropName)) { string[] temps = allDBClassPropToTableAttr[fullClassPropName].Split('.'); HashSet<string> attrList = new HashSet<string>(); attrList.Add(temps[1]); basictMethod = new BasicMethod(Constants.BasicMethodType.Get, tableName, attrList); } } if (setSelfFiels.Count() == 1 && getSelfFiels.Count() == 0) { VariableDeclaration para = setSelfFiels.SingleOrDefault(); string fullClassPropName = curClassName + "." + para.Name; if (allDBClassPropToTableAttr.ContainsKey(fullClassPropName)) { string[] temps = allDBClassPropToTableAttr[fullClassPropName].Split('.'); HashSet<string> attrList = new HashSet<string>(); attrList.Add(temps[1]); basictMethod = new BasicMethod(Constants.BasicMethodType.Set, tableName, attrList); } } } return basictMethod; }
/// <summary> /// Check if the given method calls Session built-in function. /// Return a list of Session Built-in Functions(sequence-reserved) /// </summary> /// <param name="md"></param> /// <param name="allDBClassToTableName"></param> /// <returns>Return null if doesn't call any Session built-in function</returns> public static List<SessionBuiltInFunction> CheckIfCallSessionBuiltInFunction(MethodDefinition md, Dictionary<string, string> allDBClassToTableName) { List<SessionBuiltInFunction> sessionFunctionList = new List<SessionBuiltInFunction>(); HashSet<string> PojoClassNames = GetPOJOClassName(allDBClassToTableName); Dictionary<string, string> varList = GetVariableListForMethod(md); //foreach (KeyValuePair<string, string> item in varList) //{ // Console.WriteLine(item.Key + " <--> " + item.Value); //} //Console.WriteLine(""); IEnumerable<Expression> expressions = from statements in md.GetDescendantsAndSelf() from expression in statements.GetExpressions() select expression; foreach (Expression expr in expressions) { Stack<SessionBuiltInFunction> fStack = new Stack<SessionBuiltInFunction>(); List<NameUse> itemsInSameLevel = new List<NameUse>(expr.GetDescendantsAndSelf<NameUse>()); int len = itemsInSameLevel.Count(); for(int i = 0; i < len; i++) { NameUse item = itemsInSameLevel[i]; //Console.WriteLine("\t" + item.Name + " || " + item.GetType()); // If use Session variable to call Session built-in functions if (item.GetType().ToString() == Constants.SrcML_NameUse) { //Console.WriteLine("\t" + item.Name + " || " + item.GetType()); if ((varList.ContainsKey(item.Name) && varList[item.Name] == Constants.Session)) { NameUse nextSibling = null; if (i != len - 1) { nextSibling = itemsInSameLevel[++i]; } if (nextSibling != null && nextSibling.GetType().ToString() == Constants.SrcML_MethodCall) { string sessionFunctionName = ((MethodCall)nextSibling).Name; // Next, find the target POJO class for normal session functions // And find query string for query session functions _FindSessionFunctionInfo(md, sessionFunctionName, i, len, itemsInSameLevel, PojoClassNames, varList, fStack, allDBClassToTableName); } } } // If use getCurrentSession() or openSession() to call Session built-in functions else if ((item.GetType().ToString() == Constants.SrcML_MethodCall) && (SessionBuiltInFunction.GetSessionFunctions.Contains(item.Name))) { NameUse nextSibling = null; if (i != len - 1) { nextSibling = itemsInSameLevel[++i]; } if (nextSibling != null && nextSibling.GetType().ToString() == Constants.SrcML_MethodCall) { string sessionFunctionName = ((MethodCall)nextSibling).Name; // Next, find the target POJO class for normal session functions // And find query string for query session functions _FindSessionFunctionInfo(md, sessionFunctionName, i, len, itemsInSameLevel, PojoClassNames, varList, fStack, allDBClassToTableName); } } } while (fStack.Count() != 0) { sessionFunctionList.Add(fStack.Pop()); } } return sessionFunctionList; }
/// <summary> /// return a set of caller /// </summary> /// <param name="m"></param> /// <returns></returns> public HashSet<MethodDefinition> ReturnCaller(MethodDefinition m) { HashSet<MethodDefinition> ret_al = new HashSet<MethodDefinition>(); int colPos = index[m]; HashSet<int> hs = _callerEdge[colPos]; foreach (int i in hs) { ret_al.Add(nodes[i]); } return ret_al; }
/// <summary> /// Get the class that defines this method /// </summary> /// <param name="method"></param> /// <returns></returns> public static TypeDefinition GetDeclaringClass(MethodDefinition method) { TypeDefinition declaringClass = method.GetAncestors<TypeDefinition>().FirstOrDefault(); return declaringClass; }
/// <summary> /// Constructor /// </summary> /// <param name="method"></param> public HibernateMethodAnalyzer(MethodDefinition method) : base(method) { }
/// <summary> /// check if the graph contains the method m /// </summary> /// <param name="m"></param> /// <returns>return the index of the given method in the CallGraph</returns> public bool ContainsMethod(MethodDefinition m) { if (m == null) { return false; } return index.ContainsKey(m); }
/// <summary> /// Checks the given method is a local method or not. /// </summary> /// <param name="md"></param> /// <returns></returns> private bool IsLocalMethod(MethodDefinition md) { TypeDefinition mdClass = md.GetAncestors<TypeDefinition>().FirstOrDefault(); Queue<TypeDefinition> classSet = new Queue<TypeDefinition>(); classSet.Enqueue(DeclaringClass); while(classSet.Any()) { TypeDefinition curClass = classSet.Dequeue(); if(mdClass.Equals(curClass)) { return true; } var parentClasses = curClass.GetParentTypes(false); foreach(var c in parentClasses) { classSet.Enqueue(c); } } return false; }
/// <summary> /// Get all the methods invoked by this methods: both locally or externally /// </summary> /// <param name="md"></param> /// <returns>Return list of method's full name</returns> public static HashSet<string> GetInvokedMethodNameInTheMethod(MethodDefinition md) { HashSet<string> invokedMethodNames = new HashSet<string>(); IEnumerable<MethodCall> mdCalls = from statments in md.GetDescendantsAndSelf() from expression in statments.GetExpressions() from call in expression.GetDescendantsAndSelf<MethodCall>() select call; foreach (MethodCall mdc in mdCalls) { MethodDefinition mDef = CallGraphUtil.FindMatchedMd(mdc); if (mDef != null) { invokedMethodNames.Add(mDef.GetFullName()); } } return invokedMethodNames; }
/// <summary> /// Add a directed edge (caller --> callee) /// </summary> /// <param name="caller"></param> /// <param name="callee"></param> public void addCallerToCalleeEdge(MethodDefinition caller, MethodDefinition callee) { callerToCalleeEdges[caller].Add(callee); }
/// <summary> /// Find the target POJO class for normal session functions /// and find query string for query session functions /// </summary> /// <param name="md"></param> /// <param name="sessionFunctionName"></param> /// <param name="i"></param> /// <param name="len"></param> /// <param name="itemsInSameLevel"></param> /// <param name="PojoClassNames"></param> /// <param name="varList"></param> /// <param name="fStack"></param> /// <param name="allDBClassToTableName"></param> private static void _FindSessionFunctionInfo(MethodDefinition md, string sessionFunctionName, int i, int len, List<NameUse> itemsInSameLevel, HashSet<string> PojoClassNames, Dictionary<string, string> varList, Stack<SessionBuiltInFunction> fStack, Dictionary<string, string> allDBClassToTableName) { string targetClassName = ""; if (SessionBuiltInFunction.NormalFunctions.Contains(sessionFunctionName)) { // When you find one session function, find the first NameUse that is a POJO class // (1) if use "String entityName" as parameter for (int j = i + 1; j < len; j++) { if (itemsInSameLevel[j].GetType().ToString() == Constants.SrcML_NameUse) { if (PojoClassNames.Contains(itemsInSameLevel[j].Name)) { targetClassName = itemsInSameLevel[j].Name; break; } } } // (2) not found in (1) && if use "Object object" as parameter if (targetClassName == "") { for (int j = i + 1; j < len; j++) { if (varList.ContainsKey(itemsInSameLevel[j].Name) && PojoClassNames.Contains(varList[itemsInSameLevel[j].Name])) { targetClassName = varList[itemsInSameLevel[j].Name]; break; } } } //Console.WriteLine("\t\t~~~~ " + varList[item.Name] + "." + sessionFunctionName + "(" + targetClassName + ")"); //sessionFunctionList.Add(new SessionBuiltInFunction(sessionFunctionName, targetClassName)); fStack.Push(new SessionBuiltInFunction(sessionFunctionName, GetTableNameFromClassName(targetClassName, allDBClassToTableName))); } else if (SessionBuiltInFunction.QueryFunctions.Contains(sessionFunctionName)) { // Note that, if it's query function, TargetClassName in fact means hql/sql string. for (int j = i + 1; j < len; j++) { var itemName = itemsInSameLevel[j].Name; if (varList.ContainsKey(itemName)) { if (varList[itemName] == "string" || varList[itemName] == "String") { targetClassName = varList[itemName]; break; } } } //Console.WriteLine("\t\t" + varList[item.Name] + "." + sessionFunctionName + "(" + targetClassName + ")"); //sessionFunctionList.Add(new SessionBuiltInFunction(sessionFunctionName, targetClassName)); fStack.Push(new SessionBuiltInFunction(sessionFunctionName, GetTableNameFromClassName(targetClassName, allDBClassToTableName))); } else { //Console.WriteLine("\t\t*** Other types of session function: " + sessionFunctionName); } }
/// <summary> /// Get all the varibles used in the methods, including /// paras, local variables, get/set field, property fields /// </summary> /// <param name="md"></param> /// <returns>link variable name to variable type</returns> public static Dictionary<string, string> GetVariableListForMethod(MethodDefinition md) { Dictionary<string, string> varList = new Dictionary<string, string>(); HibernateMethodAnalyzer mAnalyzer = new HibernateMethodAnalyzer(md); foreach (VariableDeclaration vi in mAnalyzer.Paras) { if (!varList.ContainsKey(vi.Name)) { varList.Add(vi.Name, vi.VariableType.ToString()); } } foreach (VariableInfo vi in mAnalyzer.VariablesInfo) { if (!varList.ContainsKey(vi.GetName())) { varList.Add(vi.GetName(), vi.GetVariableType().ToString()); } } foreach (VariableDeclaration vi in mAnalyzer.GetSelfFields) { if (!varList.ContainsKey(vi.Name)) { varList.Add(vi.Name, vi.VariableType.ToString()); } } foreach (VariableDeclaration vi in mAnalyzer.SetSelfFields) { if (!varList.ContainsKey(vi.Name)) { varList.Add(vi.Name, vi.VariableType.ToString()); } } foreach (VariableDeclaration vi in mAnalyzer.PropertyFields) { if (!varList.ContainsKey(vi.Name)) { varList.Add(vi.Name, vi.VariableType.ToString()); } } return varList; }
/// <summary> /// A recursive helper for topoSort /// </summary> /// <param name="m"></param> /// <param name="visited"></param> /// <param name="topToBottom"></param> private void topoSortHelper(MethodDefinition m, Dictionary<MethodDefinition, bool> visited, Stack<MethodDefinition> topToBottom) { // Mark the current method as visited visited[m] = true; List<MethodDefinition> calleeList = callerToCalleeEdges[m]; foreach (MethodDefinition callee in calleeList) { if (!visited[callee]) { topoSortHelper(callee, visited, topToBottom); } } topToBottom.Push(m); }
/// <summary> /// Get all the methods invoked by this methods: both locally or externally /// Using MethodAnalyzer. Sometimes doesn't work!!! /// </summary> /// <param name="md"></param> /// <returns></returns> public static HashSet<string> GetInvokedMethodNameInTheMethod_Stale(MethodDefinition md) { HashSet<string> invokedMethodNames = new HashSet<string>(); HibernateMethodAnalyzer mAnalyzer = new HibernateMethodAnalyzer(md); foreach (MethodDefinition invmd in mAnalyzer.InvokedLocalMethods) { if (invmd != null) { invokedMethodNames.Add(invmd.GetFullName()); } } foreach (MethodDefinition invmd in mAnalyzer.InvokedExternalMethods) { if (invmd != null) { invokedMethodNames.Add(invmd.GetFullName()); } } return invokedMethodNames; }
/// <summary> /// Add a method (act as a node in the graph) /// </summary> /// <param name="m"></param> public void addMethod(MethodDefinition m) { methods.Add(m); callerToCalleeEdges.Add(m, new List<MethodDefinition>()); }
/// <summary> /// Given a method, return its passed-in parameters /// </summary> /// <param name="method"></param> /// <returns></returns> public static IReadOnlyCollection<VariableDeclaration> GetParametersInitialInfo(MethodDefinition method) { return method.Parameters; }