private static string GetTypeParameterDeclsAsString(AstNodeCollection<TypeParameterDeclaration> parameterDecls) { var parameterString = new StringBuilder(); int current = 0; foreach (var paramDecl in parameterDecls) { parameterString.Append(paramDecl.NameToken.ToString()); if (current < (parameterDecls.Count - 1)) { parameterString.Append(", "); } current++; } return parameterString.ToString(); }
private static string GetParameterDeclsAsString(AstNodeCollection<ParameterDeclaration> parameterDecls) { var parameterString = new StringBuilder(); int current = 0; foreach (var paramDecl in parameterDecls) { if (paramDecl.ParameterModifier != ParameterModifier.None) { parameterString.Append(paramDecl.ParameterModifier.ToString().ToLower()); parameterString.Append(" "); } parameterString.Append(paramDecl.Type.ToString()); parameterString.Append(" "); parameterString.Append(paramDecl.Name); if (current < (parameterDecls.Count - 1)) { parameterString.Append(", "); } current++; } return parameterString.ToString(); }
protected virtual void FixMethodParameters(AstNodeCollection<ParameterDeclaration> parameters, BlockStatement body) { /*if (parameters.Count == 0) { return; } foreach (var p in parameters) { string newName = Emitter.FIX_ARGUMENT_NAME + p.Name; string oldName = p.Name; VariableDeclarationStatement varState = new VariableDeclarationStatement(p.Type.Clone(), oldName, new CastExpression(p.Type.Clone(), new IdentifierExpression(newName))); p.Name = newName; body.InsertChildBefore(body.FirstChild, varState, new Role<VariableDeclarationStatement>("Statement")); }*/ }
protected virtual ICSharpCode.NRefactory.CSharp.Attribute GetAttribute(AstNodeCollection<AttributeSection> attributes, string name) { string fullName = name + "Attribute"; foreach (var i in attributes) { foreach (var j in i.Attributes) { if (j.Type.ToString() == name) { return j; } var resolveResult = this.Resolver.ResolveNode(j, this); if (resolveResult != null && resolveResult.Type != null && resolveResult.Type.FullName == fullName) { return j; } } } return null; }
void AnalyzeExpression(AstNode expression, AstNode body, AstNodeCollection<ParameterDeclaration> parameters) { var invocation = AnalyzeBody(body); if (invocation == null) return; if (!IsSimpleTarget (invocation.Target)) return; var lambdaParameters = parameters.ToList(); if (lambdaParameters.Count != invocation.Arguments.Count) return; int i = 0; foreach (var param in invocation.Arguments) { var id = param as IdentifierExpression; if (id == null) return; if (lambdaParameters[i].Name != id.Identifier) return; i++; } AddIssue(expression, ctx.TranslateString("Expression can be reduced to delegate"), script => { script.Replace(expression, invocation.Target.Clone()); }); }
void PrintInitializerElements(AstNodeCollection<Expression> elements) { PrintInitializerElements (elements, Roles.LBrace, Roles.RBrace); }
void RemoveCompilerGeneratedAttribute(AstNodeCollection <AttributeSection> attributeSections) { RemoveCompilerGeneratedAttribute(attributeSections, "System.Runtime.CompilerServices.CompilerGeneratedAttribute"); }
private void FillMembersComboBox() { EntityDeclaration c = GetCurrentSelectedClass(); if (c != null && _lastClassInMembersComboBox != c) { _lastClassInMembersComboBox = c; ArrayList items = new ArrayList(); bool partialMode = false; EntityDeclaration currentPart = c; //if (c.iIsPartial) //{ // CompoundClass cc = c.GetCompoundClass() as CompoundClass; // if (cc != null) // { // partialMode = true; // c = cc; // } //} // TODO lock has been removed... //lock (c) { if (c.GetType() == typeof(DelegateDeclaration)) { DelegateDeclaration de = (DelegateDeclaration)c; if (de != null) { items.Add(new ComboBoxItem(de, de.Name, (int)0, true, "delegate")); } } if (c.GetType() == typeof(TypeDeclaration)) { TypeDeclaration dd = (TypeDeclaration)c; int lastIndex = 0; IComparer comparer = new Comparer(System.Globalization.CultureInfo.InvariantCulture); foreach (EntityDeclaration m in dd.Members) { Type T = m.GetType(); if (m.GetType() == typeof(MethodDeclaration)) { items.Add(new ComboBoxItem(m, m.Name, (int)0, true, "method")); } //items.Sort(lastIndex, c.Methods.Count, comparer); lastIndex = items.Count; if (m.GetType() == typeof(ConstructorDeclaration)) { items.Add(new ComboBoxItem(m, m.Name, (int)0, true, "Class")); } //items.Sort(lastIndex, c.Methods.Count, comparer); lastIndex = items.Count; if (m.GetType() == typeof(PropertyDeclaration)) { items.Add(new ComboBoxItem(m, m.Name, (int)0, true, "property")); } //items.Sort(lastIndex, c.Properties.Count, comparer); lastIndex = items.Count; if (m.GetType() == typeof(FieldDeclaration)) { string s = m.Name; FieldDeclaration g = (FieldDeclaration)m; if (g.Variables != null) { if (g.Variables.Count > 0) { AstNodeCollection <VariableInitializer> v = g.Variables; foreach (VariableInitializer vv in v) { s = vv.Name; } } } items.Add(new ComboBoxItem(m, s, (int)0, true, "Class")); } //items.Sort(lastIndex, c.Fields.Count, comparer); lastIndex = items.Count; if (m.GetType() == typeof(EventDeclaration)) { items.Add(new ComboBoxItem(m, m.Name, (int)0, true, "Class")); } } //items.Sort(lastIndex, c.Events.Count, comparer); lastIndex = items.Count; } } _membersComboBox.BeginUpdate(); _membersComboBox.Items.Clear(); _membersComboBox.Items.AddRange(items.ToArray()); _membersComboBox.EndUpdate(); UpdateMembersComboBox(); } }
public static void Main(string[] args) { if (FixUtil.Instance.NeedFix("Program.Main")) { string strParameter = string.Format("Program,Main,{0},{1}", typeof(object), typeof(string[])); FixUtil.Instance.Fix(strParameter, null, args); return; } /* * if (args.Length == 0) { * Console.WriteLine("Please specify the path to a .sln file on the command line"); * * Console.Write("Press any key to continue . . . "); * Console.ReadKey(true); * return; * } * */ List <string> list = new List <string>(); Solution solution = new Solution("C:\\Martin\\GitHub\\HotFixForUnity\\AddMethodTool\\AddMethod.sln"); //Solution solution = new Solution(args[0]); // foreach (var file in solution.AllFiles) { // var astResolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile); // foreach (var invocation in file.SyntaxTree.Descendants.OfType<InvocationExpression>()) { // // Retrieve semantics for the invocation // var rr = astResolver.Resolve(invocation) as InvocationResolveResult; // if (rr == null) { // // Not an invocation resolve result - e.g. could be a UnknownMemberResolveResult instead // continue; // } // if (rr.Member.FullName != "System.String.IndexOf") { // // Invocation isn't a string.IndexOf call // continue; // } // if (rr.Member.Parameters.First().Type.FullName != "System.String") { // // Ignore the overload that accepts a char, as that doesn't take a StringComparison. // // (looking for a char always performs the expected ordinal comparison) // continue; // } // if (rr.Member.Parameters.Last().Type.FullName == "System.StringComparison") { // // Already using the overload that specifies a StringComparison // continue; // } // Console.WriteLine(invocation.GetRegion() + ": " + invocation.GetText()); // file.IndexOfInvocations.Add(invocation); // } // } // Console.WriteLine("Found {0} places to refactor in {1} files.", // solution.AllFiles.Sum(f => f.IndexOfInvocations.Count), // solution.AllFiles.Count(f => f.IndexOfInvocations.Count > 0)); Console.Write("Apply refactorings? "); //string answer = Console.ReadLine(); //if ("yes".Equals(answer, StringComparison.OrdinalIgnoreCase) || "y".Equals(answer, StringComparison.OrdinalIgnoreCase)) { foreach (var file in solution.AllFiles) { // if (file.IndexOfInvocations.Count == 0) // continue; // DocumentScript expects the the AST to stay unmodified (so that it fits // to the document state at the time of the DocumentScript constructor call), // so we call Freeze() to prevent accidental modifications (e.g. forgetting a Clone() call). file.SyntaxTree.Freeze(); // AST resolver used to find context for System.StringComparison generation var compilation = file.Project.Compilation; var astResolver = new CSharpAstResolver(compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile); // Create a document containing the file content: var document = new StringBuilderDocument(file.OriginalText); var formattingOptions = FormattingOptionsFactory.CreateAllman(); var options = new TextEditorOptions(); // using (var script = new DocumentScript(document, formattingOptions, options)) { // foreach (InvocationExpression expr in file.IndexOfInvocations) { // // Generate a reference to System.StringComparison in this context: // var astBuilder = new TypeSystemAstBuilder(astResolver.GetResolverStateBefore(expr)); // IType stringComparison = compilation.FindType(typeof(StringComparison)); // AstType stringComparisonAst = astBuilder.ConvertType(stringComparison); // // // Alternative 1: clone a portion of the AST and modify it // var copy = (InvocationExpression)expr.Clone(); // copy.Arguments.Add(stringComparisonAst.Member("Ordinal")); // script.Replace(expr, copy); // // // // Alternative 2: perform direct text insertion // // int offset = script.GetCurrentOffset(expr.RParToken.StartLocation); // // script.InsertText(offset, ", " + stringComparisonAst.GetText() + ".Ordinal"); // } // } using (var script = new DocumentScript(document, formattingOptions, options)) { CSharpParser parser = new CSharpParser(); //SyntaxTree syntaxTree = parser.Parse(code, srcFilePath); SyntaxTree syntaxTree = file.SyntaxTree; foreach (var classDec in syntaxTree.Descendants.OfType <TypeDeclaration>()) { if (classDec.ClassType == ClassType.Class || classDec.ClassType == ClassType.Struct) { var className = classDec.Name; foreach (var method in classDec.Children.OfType <MethodDeclaration>()) { var returnType = method.ReturnType.ToString(); if (returnType.Contains("IEnumerator") || returnType.Contains("IEnumerable")) // 暂不支持yield! { continue; } Console.WriteLine("className:" + className + " method:" + method.Name); AstNodeCollection <ParameterDeclaration> paramlist = method.Parameters; string strParaType = string.Format("{0},{1}", className, method.Name); string numberType = ",{0}"; string numberPara = ", typeof(object)"; string strPara = ", null"; if ((method.Modifiers & Modifiers.Static) != Modifiers.Static) { strPara = ", this"; } int number = 1; foreach (ParameterDeclaration param in paramlist) { Console.WriteLine("param " + param.Name); strPara += string.Format(", {0}", param.Name); numberType += string.Format(",{0}{1}{2}", "{", number, "}"); numberPara += string.Format(", typeof({0})", param.Type); number++; } int offset = script.GetCurrentOffset(method.Body.LBraceToken.StartLocation); script.InsertText(offset + 1, "\n" + "\n" + string.Format("if (FixUtil.Instance.NeedFix(\"{0}.{1}\"))\n", className, method.Name) + "{\n" + string.Format(" string strParameter = string.Format(\"{0}{1}\"{2});\n", strParaType, numberType, numberPara) + string.Format(" FixUtil.Instance.Fix(strParameter{0});\n", strPara) + " return;\n" + "}\n"); // script.InsertText(offset + 1, "\n" + // "\n" + // string.Format("if (FixUtil.Instance.NeedFix("+className+"."+method.Name+"))\n" + // "{\n" + // string.Format(" FixUtil.Instance.Fix(\"{0}.{1}\"{2});\n", className, method.Name, str) + // " return;\n" + // "}\n"); } } } } File.WriteAllText(Path.ChangeExtension(file.FileName, ".output.cs"), document.Text); } string text = Console.ReadLine(); } }
protected void VisitObjectCreateExpression() { ObjectCreateExpression objectCreateExpression = this.ObjectCreateExpression; var resolveResult = this.Emitter.Resolver.ResolveNode(objectCreateExpression.Type, this.Emitter) as TypeResolveResult; if (resolveResult != null && resolveResult.Type.Kind == TypeKind.Enum) { this.Write("(0)"); return; } bool isTypeParam = resolveResult != null && resolveResult.Type.Kind == TypeKind.TypeParameter; var invocationResolveResult = this.Emitter.Resolver.ResolveNode(objectCreateExpression, this.Emitter) as InvocationResolveResult; if (isTypeParam && invocationResolveResult != null && invocationResolveResult.Member.Parameters.Count == 0) { this.Write(JS.Funcs.BRIDGE_CREATEINSTANCE); this.WriteOpenParentheses(); this.Write(resolveResult.Type.Name); this.WriteCloseParentheses(); return; } var type = isTypeParam ? null : this.Emitter.GetTypeDefinition(objectCreateExpression.Type); var isObjectLiteral = type != null && this.Emitter.Validator.IsObjectLiteral(type); if (type != null && type.BaseType != null && type.BaseType.FullName == "System.MulticastDelegate") { bool wrap = false; var parent = objectCreateExpression.Parent as InvocationExpression; if (parent != null && parent.Target == objectCreateExpression) { wrap = true; } if (wrap) { this.WriteOpenParentheses(); } objectCreateExpression.Arguments.First().AcceptVisitor(this.Emitter); if (wrap) { this.WriteCloseParentheses(); } return; } var argsInfo = new ArgumentsInfo(this.Emitter, objectCreateExpression); var argsExpressions = argsInfo.ArgumentsExpressions; var paramsArg = argsInfo.ParamsExpression; string inlineCode = null; if (invocationResolveResult != null) { if (invocationResolveResult.Member.DeclaringType.Kind == TypeKind.Struct && objectCreateExpression.Arguments.Count == 0) { var ctors = invocationResolveResult.Member.DeclaringType.GetConstructors(c => c.Parameters.Count == 1); var defCtor = ctors.FirstOrDefault(c => c.Parameters.First().Type.FullName == "System.Runtime.CompilerServices.DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor"); if (defCtor != null) { inlineCode = this.Emitter.GetInline(defCtor); } } if (inlineCode == null) { inlineCode = this.Emitter.GetInline(invocationResolveResult.Member); } } var customCtor = isTypeParam ? "" : (this.Emitter.Validator.GetCustomConstructor(type) ?? ""); var hasInitializer = !objectCreateExpression.Initializer.IsNull && objectCreateExpression.Initializer.Elements.Count > 0; bool isCollectionInitializer = false; AstNodeCollection <Expression> elements = null; if (hasInitializer) { elements = objectCreateExpression.Initializer.Elements; isCollectionInitializer = elements.Count > 0 && elements.First() is ArrayInitializerExpression; } var isPlainObjectCtor = Regex.Match(customCtor, @"\s*\{\s*\}\s*").Success; var isPlainMode = this.Emitter.Validator.GetObjectCreateMode(type) == 0; if (inlineCode == null && isPlainObjectCtor && isPlainMode) { this.WriteOpenBrace(); this.WriteSpace(); this.WriteObjectInitializer(objectCreateExpression.Initializer.Elements, type, invocationResolveResult, false); this.WriteSpace(); this.WriteCloseBrace(); } else { if (hasInitializer) { this.Write(JS.Funcs.BRIDGE_MERGE); this.WriteOpenParentheses(); } if (inlineCode != null) { new InlineArgumentsBlock(this.Emitter, argsInfo, inlineCode).Emit(); } else { var ctorMember = ((InvocationResolveResult)this.Emitter.Resolver.ResolveNode(objectCreateExpression, this.Emitter)).Member; var expandParams = ctorMember.Attributes.Any(a => a.AttributeType.FullName == "Bridge.ExpandParamsAttribute"); bool applyCtor = false; if (expandParams) { var ctor_rr = this.Emitter.Resolver.ResolveNode(paramsArg, this.Emitter); if (ctor_rr.Type.Kind == TypeKind.Array && !(paramsArg is ArrayCreateExpression) && objectCreateExpression.Arguments.Last() == paramsArg) { this.Write(JS.Types.Bridge.Reflection.APPLYCONSTRUCTOR + "("); applyCtor = true; } } if (String.IsNullOrEmpty(customCtor) || (isObjectLiteral && isPlainObjectCtor)) { if (!applyCtor && !isObjectLiteral) { this.WriteNew(); } var typerr = this.Emitter.Resolver.ResolveNode(objectCreateExpression.Type, this.Emitter).Type; var isGeneric = typerr.TypeArguments.Count > 0 && !Helpers.IsIgnoreGeneric(typerr, this.Emitter); if (isGeneric && !applyCtor) { this.WriteOpenParentheses(); } objectCreateExpression.Type.AcceptVisitor(this.Emitter); if (isGeneric && !applyCtor) { this.WriteCloseParentheses(); } } else { this.Write(customCtor); } if (!isTypeParam && !this.Emitter.Validator.IsIgnoreType(type) && type.Methods.Count(m => m.IsConstructor && !m.IsStatic) > (type.IsValueType || isObjectLiteral ? 0 : 1)) { this.WriteDot(); var name = OverloadsCollection.Create(this.Emitter, ((InvocationResolveResult)this.Emitter.Resolver.ResolveNode(objectCreateExpression, this.Emitter)).Member).GetOverloadName(); this.Write(name); } if (applyCtor) { this.Write(", "); } else { this.WriteOpenParentheses(); } new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, objectCreateExpression, -1).Emit(); this.WriteCloseParentheses(); } if (hasInitializer) { this.WriteComma(); bool needComma = false; if (isCollectionInitializer && !isObjectLiteral) { this.Write("["); this.WriteNewLine(); this.Indent(); } else { this.BeginBlock(); } List <string> inlineInit = new List <string>(); if (isObjectLiteral) { this.WriteObjectInitializer(objectCreateExpression.Initializer.Elements, type, invocationResolveResult, true); } else { foreach (Expression item in elements) { if (needComma) { this.WriteComma(true); } needComma = true; inlineCode = ObjectCreateBlock.GetInlineInit(item, this); if (inlineCode != null) { inlineInit.Add(inlineCode); } else if (item is NamedExpression) { var namedExpression = (NamedExpression)item; new NameBlock(this.Emitter, namedExpression.Name, namedExpression, namedExpression.Expression, true).Emit(); } else if (item is NamedArgumentExpression) { var namedArgumentExpression = (NamedArgumentExpression)item; new NameBlock(this.Emitter, namedArgumentExpression.Name, namedArgumentExpression, namedArgumentExpression.Expression, true).Emit(); } else if (item is ArrayInitializerExpression) { var arrayInitializer = (ArrayInitializerExpression)item; this.Write("["); foreach (var el in arrayInitializer.Elements) { this.EnsureComma(false); el.AcceptVisitor(this.Emitter); this.Emitter.Comma = true; } this.Write("]"); this.Emitter.Comma = false; } else if (item is IdentifierExpression) { var identifierExpression = (IdentifierExpression)item; new IdentifierBlock(this.Emitter, identifierExpression).Emit(); } } } this.WriteNewLine(); if (isCollectionInitializer && !isObjectLiteral) { this.Outdent(); this.Write("]"); } else { this.EndBlock(); } if (inlineInit.Count > 0) { this.Write(", function () "); this.BeginBlock(); foreach (var init in inlineInit) { this.Write(init); this.WriteNewLine(); } this.EndBlock(); } this.WriteSpace(); this.WriteCloseParentheses(); } } //Helpers.CheckValueTypeClone(invocationResolveResult, this.ObjectCreateExpression, this, pos); }
private void AddMethod(bool ctor, EntityDeclaration methodDeclaration, AstNodeCollection<ParameterDeclaration> parameters) { CLRType t = m_clrTypes.Value.Last.Value; List<KeyValuePair<string, string>> args = parameters.Select(p => new KeyValuePair<string, string>(p.Name, p.Type.ToString()) ) .ToList(); Method m = new Method( CheckFlag(methodDeclaration.Modifiers, Modifiers.Override), ctor, CheckFlag(methodDeclaration.Modifiers, Modifiers.Static), new Visibility(VisibilityMapper.Map(methodDeclaration.Modifiers)), CheckFlag(methodDeclaration.Modifiers, Modifiers.Virtual), methodDeclaration.Name, CheckFlag(methodDeclaration.Modifiers, Modifiers.Abstract), args, methodDeclaration.ReturnType.ToString() ); t.Methods.Add(m); // connect }
private void MangleStatement(AstNodeCollection<Statement> statements, AstNode node) { // Remove stray semicolons if (node is EmptyStatement) { node.Remove(); return; } // Inline nested block statements var block = node as BlockStatement; if (block != null) { foreach (var replacement in block.Statements) { replacement.Remove(); statements.InsertBefore((Statement)node, replacement); } node.Remove(); return; } // Merge adjacent variable declarations var declaration = node as VariableDeclarationStatement; if (declaration != null) { var previous = PreviousSiblingIgnoringWhitespace(node) as VariableDeclarationStatement; if (previous != null) { foreach (var variable in declaration.Variables) { variable.Remove(); previous.Variables.Add(variable); } if (node.PrevSibling is NewLineNode) { node.PrevSibling.Remove(); } node.Remove(); } return; } // Bring previous variable declarations into for loops var loop = node as ForStatement; if (loop != null) { var previous = PreviousSiblingIgnoringWhitespace(node) as VariableDeclarationStatement; if (previous != null) { var count = loop.Initializers.Count; if (count == 0) { previous.Remove(); loop.Initializers.Add(previous); } else if (count == 1) { var initializers = loop.Initializers.FirstOrNullObject() as VariableDeclarationStatement; if (initializers != null) { foreach (var variable in initializers.Variables) { variable.Remove(); previous.Variables.Add(variable); } previous.Remove(); initializers.Remove(); loop.Initializers.Add(previous); } } } return; } }
void VisitParameterizedEntityDeclaration(string memberType, EntityDeclaration entityDeclaration, AstNodeCollection <ParameterDeclaration> parameters) { //Override is not strictly necessary because methodDeclaration //might still implement an interface member var memberResolveResult = ctx.Resolve(entityDeclaration) as MemberResolveResult; if (memberResolveResult == null) { return; } var member = (IParameterizedMember)memberResolveResult.Member; var baseMembers = InheritanceHelper.GetBaseMembers(member, true); foreach (IParameterizedMember baseMember in baseMembers) { if (baseMember.IsOverride || baseMember.DeclaringType.Kind == TypeKind.Interface) { continue; } CompareMethods(memberType, parameters, member, baseMember); return; } // only check 1 interface method -> multiple interface implementations could lead to deault value conflicts // possible other solutions: Skip the interface check entirely var interfaceBaseMethods = baseMembers.Where(b => b.DeclaringType.Kind == TypeKind.Interface).ToList(); if (interfaceBaseMethods.Count == 1) { foreach (IParameterizedMember baseMember in interfaceBaseMethods) { if (baseMember.DeclaringType.Kind == TypeKind.Interface) { CompareMethods(memberType, parameters, member, baseMember); } } } }
public AccessorDeclaration() { Parameters = new AstNodeCollection<Ast.Members.ParameterDeclaration>(this, AstNodeTitles.Parameter); }
JsonValue GetInitializerElements(AstNodeCollection<Expression> elements) { JsonArray initArr = new JsonArray(); foreach (AstNode node in elements) { node.AcceptVisitor(this); initArr.AddJsonValue(Pop()); } if (initArr.Count == 0) { initArr = null; } return initArr; }
public static List<AstType> ExtractAllTypesFrom(AstNodeCollection<Expression> elist) { List<AstType> result = new List<AstType>(); foreach (Expression e in elist) { result.AddRange(ExtractAllTypesFrom(e)); } return result; }
public static List<Expression> ConvertToExternTypeArguments(AstNodeCollection<ParameterDeclaration> parameters) { List<Expression> arguments = new List<Expression>(); foreach (ParameterDeclaration p in parameters) { if (Resolver.GetTypeName(p.Type).Equals("Array")) { if (p.Type is PtrType) { arguments.Add(new PointerExpression(new IdentifierExpression(p.Name))); } } else { arguments.Add(new IdentifierExpression(p.Name)); } } return arguments; }
void PrintInitializerElements(AstNodeCollection<Expression> elements, bool square = false) { BraceStyle style; if (policy.ArrayInitializerWrapping == Wrapping.WrapAlways) { style = BraceStyle.NextLine; } else { style = BraceStyle.EndOfLine; } if (!square) OpenBrace(style); else WriteToken(Roles.LBracket); bool isFirst = true; AstNode last = null; foreach (AstNode node in elements) { if (isFirst) { isFirst = false; } else { Comma(node, noSpaceAfterComma: true); NewLine(); } last = node; node.AcceptVisitor(this); } if (last != null) OptionalComma(last.NextSibling); NewLine(); if (!square) { CloseBrace(style); } else WriteToken(Roles.RBracket); }
protected void VisitObjectCreateExpression() { ObjectCreateExpression objectCreateExpression = ObjectCreateExpression; var resolveResult = Emitter.Resolver.ResolveNode(objectCreateExpression.Type) as TypeResolveResult; if (resolveResult != null && resolveResult.Type.Kind == TypeKind.Enum) { Write("(0)"); return; } bool isTypeParam = resolveResult != null && resolveResult.Type.Kind == TypeKind.TypeParameter; var invocationResolveResult = Emitter.Resolver.ResolveNode(objectCreateExpression) as InvocationResolveResult; var hasInitializer = !objectCreateExpression.Initializer.IsNull && objectCreateExpression.Initializer.Elements.Count > 0; if (isTypeParam && invocationResolveResult != null && invocationResolveResult.Member.Parameters.Count == 0 && !hasInitializer) { Write(JS.Funcs.H5_CREATEINSTANCE); WriteOpenParentheses(); Write(resolveResult.Type.Name); WriteCloseParentheses(); return; } var type = isTypeParam ? null : Emitter.GetTypeDefinition(objectCreateExpression.Type); var isObjectLiteral = type != null && Emitter.Validator.IsObjectLiteral(type); if (type != null && type.BaseType != null && type.BaseType.FullName == "System.MulticastDelegate") { bool wrap = false; if (objectCreateExpression.Parent is InvocationExpression parent && parent.Target == objectCreateExpression) { wrap = true; } if (wrap) { WriteOpenParentheses(); } Write("H5.fn.$build(["); objectCreateExpression.Arguments.First().AcceptVisitor(Emitter); Write("])"); if (wrap) { WriteCloseParentheses(); } return; } var argsInfo = new ArgumentsInfo(Emitter, objectCreateExpression); var argsExpressions = argsInfo.ArgumentsExpressions; var paramsArg = argsInfo.ParamsExpression; string inlineCode = null; if (invocationResolveResult != null) { if (invocationResolveResult.Member.DeclaringType.Kind == TypeKind.Struct && objectCreateExpression.Arguments.Count == 0) { var ctors = invocationResolveResult.Member.DeclaringType.GetConstructors(c => c.Parameters.Count == 1); var defCtor = ctors.FirstOrDefault(c => c.Parameters.First().Type.FullName == "System.Runtime.CompilerServices.DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor"); if (defCtor != null) { inlineCode = Emitter.GetInline(defCtor); } } if (inlineCode == null) { inlineCode = Emitter.GetInline(invocationResolveResult.Member); } } var customCtor = isTypeParam ? "" : (Emitter.Validator.GetCustomConstructor(type) ?? ""); AstNodeCollection <Expression> elements = null; if (hasInitializer) { elements = objectCreateExpression.Initializer.Elements; } var isPlainObjectCtor = Regex.Match(customCtor, @"\s*\{\s*\}\s*").Success; var isPlainMode = type != null && Emitter.Validator.GetObjectCreateMode(type) == 0; if (inlineCode == null && isPlainObjectCtor && isPlainMode) { WriteOpenBrace(); WriteSpace(); var pos = Emitter.Output.Length; WriteObjectInitializer(objectCreateExpression.Initializer.Elements, type, invocationResolveResult, false); if (pos < Emitter.Output.Length) { WriteSpace(); } WriteCloseBrace(); } else { string tempVar = null; if (hasInitializer) { tempVar = GetTempVarName(); WriteOpenParentheses(); Write(tempVar); Write(" = "); } if (inlineCode != null) { new InlineArgumentsBlock(Emitter, argsInfo, inlineCode).Emit(); } else { var ctorMember = ((InvocationResolveResult)Emitter.Resolver.ResolveNode(objectCreateExpression)).Member; var expandParams = ctorMember.Attributes.Any(a => a.AttributeType.FullName == "H5.ExpandParamsAttribute"); bool applyCtor = false; if (expandParams) { var ctor_rr = Emitter.Resolver.ResolveNode(paramsArg); if (ctor_rr.Type.Kind == TypeKind.Array && !(paramsArg is ArrayCreateExpression) && objectCreateExpression.Arguments.Last() == paramsArg) { Write(JS.Types.H5.Reflection.APPLYCONSTRUCTOR + "("); applyCtor = true; } } if (String.IsNullOrEmpty(customCtor) || (isObjectLiteral && isPlainObjectCtor)) { if (!applyCtor && !isObjectLiteral) { WriteNew(); } var typerr = Emitter.Resolver.ResolveNode(objectCreateExpression.Type).Type; var td = typerr.GetDefinition(); var isGeneric = typerr.TypeArguments.Count > 0 && !Helpers.IsIgnoreGeneric(typerr, Emitter) || td != null && Validator.IsVirtualTypeStatic(td); if (isGeneric && !applyCtor) { WriteOpenParentheses(); } objectCreateExpression.Type.AcceptVisitor(Emitter); if (isGeneric && !applyCtor) { WriteCloseParentheses(); } } else { Write(customCtor); } if (!isTypeParam && type.Methods.Count(m => m.IsConstructor && !m.IsStatic) > (type.IsValueType || isObjectLiteral ? 0 : 1)) { var member = ((InvocationResolveResult)Emitter.Resolver.ResolveNode(objectCreateExpression)).Member; if (!Emitter.Validator.IsExternalType(type) || member.Attributes.Any(a => a.AttributeType.FullName == "H5.NameAttribute")) { WriteDot(); var name = OverloadsCollection.Create(Emitter, member).GetOverloadName(); Write(name); } } if (applyCtor) { Write(", "); } else { WriteOpenParentheses(); } new ExpressionListBlock(Emitter, argsExpressions, paramsArg, objectCreateExpression, -1).Emit(); WriteCloseParentheses(); } if (hasInitializer) { if (isObjectLiteral && isPlainMode) { WriteObjectInitializer(objectCreateExpression.Initializer.Elements, type, invocationResolveResult, true); } else { foreach (Expression item in elements) { WriteInitializerExpression(item, tempVar); } } WriteComma(); Write(tempVar); WriteCloseParentheses(); RemoveTempVar(tempVar); } } //Helpers.CheckValueTypeClone(invocationResolveResult, this.ObjectCreateExpression, this, pos); }
/// <inheritdoc/> protected override void WriteMethodHeader(String methodName, AstNodeCollection <ParameterDeclaration> parameters) { Formatter.AppendName(methodName); WriteCommaSeparatedListInParenthesis(parameters); }
private List <JStatement> VisitStatements(AstNodeCollection <Statement> list) { return(list.Select(VisitStatement).ToList()); }
public static bool LayoutTypeQualifiersAreEquivalent(AstNodeCollection <LayoutIdQualifier> layout1, AstNodeCollection <LayoutIdQualifier> layout2) { if ((layout1 == null || layout1.Count == 0) && (layout2 == null || layout2.Count == 0)) { return(true); } if (layout1?.Count != layout2?.Count) { return(false); } Dictionary <string, IntegerLiteral> l1 = new Dictionary <string, IntegerLiteral>(); Dictionary <string, IntegerLiteral> l2 = new Dictionary <string, IntegerLiteral>(); var addDelegate = new Action <AstNodeCollection <LayoutIdQualifier>, Dictionary <string, IntegerLiteral>, int>((l, d, ix) => { var name = l[ix].Identifier?.Name ?? string.Empty; if (!d.ContainsKey(name)) { d.Add(name, l[ix].Order); } else { d[name] = l[ix].Order; } }); for (var i = 0; i < layout1.Count; i++) { addDelegate(layout1, l1, i); addDelegate(layout2, l2, i); } if (l1.Count != l2.Count) { return(false); } foreach (var key in l1.Keys) { if (!l2.ContainsKey(key)) { return(false); } if (!IntegerLiteralsAreEquivalent(l1[key], l2[key])) { return(false); } } return(true); }
void RemoveCompilerGeneratedAttribute(AstNodeCollection<AttributeSection> attributeSections) { foreach (AttributeSection section in attributeSections) { foreach (var attr in section.Attributes) { TypeReference tr = attr.Type.Annotation<TypeReference>(); if (tr != null && tr.Namespace == "System.Runtime.CompilerServices" && tr.Name == "CompilerGeneratedAttribute") { attr.Remove(); } } if (section.Attributes.Count == 0) section.Remove(); } }
protected virtual void PrintInitializerElements(AstNodeCollection<Expression> elements, CodeBracesRangeFlags flags) { BraceStyle style; if (policy.ArrayInitializerWrapping == Wrapping.WrapAlways) { style = BraceStyle.NextLine; } else { style = BraceStyle.EndOfLine; } var braceHelper = OpenBrace(style, flags); bool isFirst = true; AstNode last = null; int count = 0; foreach (AstNode node in elements) { if (count-- <= 0) { cancellationToken.ThrowIfCancellationRequested(); count = CANCEL_CHECK_LOOP_COUNT; } if (isFirst) { isFirst = false; } else { Comma(node, noSpaceAfterComma: true); NewLine(); } last = node; node.AcceptVisitor(this); } if (last != null) OptionalComma(last.NextSibling); NewLine(); CloseBrace(style, braceHelper, false); }
public ILVCallExpression(VCallAnnotation annotation) : base(annotation.ReturnType) { Annotation = annotation; Arguments = new AstNodeCollection <ILExpression>(this); }
protected void VisitObjectCreateExpression() { ObjectCreateExpression objectCreateExpression = this.ObjectCreateExpression; var resolveResult = this.Emitter.Resolver.ResolveNode(objectCreateExpression.Type, this.Emitter) as TypeResolveResult; bool isTypeParam = resolveResult.Type.Kind == TypeKind.TypeParameter; var type = isTypeParam ? null : this.Emitter.GetTypeDefinition(objectCreateExpression.Type); if (type != null && type.BaseType != null && type.BaseType.FullName == "System.MulticastDelegate") { bool wrap = false; var parent = objectCreateExpression.Parent as InvocationExpression; if (parent != null && parent.Target == objectCreateExpression) { wrap = true; } if (wrap) { this.WriteOpenParentheses(); } objectCreateExpression.Arguments.First().AcceptVisitor(this.Emitter); if (wrap) { this.WriteCloseParentheses(); } return; } var argsInfo = new ArgumentsInfo(this.Emitter, objectCreateExpression); var argsExpressions = argsInfo.ArgumentsExpressions; var argsNames = argsInfo.ArgumentsNames; var paramsArg = argsInfo.ParamsExpression; var argsCount = argsExpressions.Count(); var invocationResolveResult = this.Emitter.Resolver.ResolveNode(objectCreateExpression, this.Emitter) as InvocationResolveResult; string inlineCode = null; if (invocationResolveResult != null) { inlineCode = this.Emitter.GetInline(invocationResolveResult.Member); } var customCtor = isTypeParam ? "" : (this.Emitter.Validator.GetCustomConstructor(type) ?? ""); var hasInitializer = !objectCreateExpression.Initializer.IsNull && objectCreateExpression.Initializer.Elements.Count > 0; bool isCollectionInitializer = false; AstNodeCollection <Expression> elements = null; if (hasInitializer) { elements = objectCreateExpression.Initializer.Elements; isCollectionInitializer = elements.Count > 0 && elements.First() is ArrayInitializerExpression; } if (inlineCode == null && Regex.Match(customCtor, @"\s*\{\s*\}\s*").Success) { this.WriteOpenBrace(); this.WriteSpace(); if (hasInitializer) { this.WriteObjectInitializer(objectCreateExpression.Initializer.Elements, this.Emitter.AssemblyInfo.PreserveMemberCase, type, invocationResolveResult); this.WriteSpace(); } else if (this.Emitter.Validator.IsObjectLiteral(type)) { this.WriteObjectInitializer(null, this.Emitter.AssemblyInfo.PreserveMemberCase, type, invocationResolveResult); this.WriteSpace(); } this.WriteCloseBrace(); } else { if (hasInitializer) { this.Write(Bridge.Translator.Emitter.ROOT); this.WriteDot(); this.Write(Bridge.Translator.Emitter.MERGE_OBJECT); this.WriteOpenParentheses(); } if (inlineCode != null) { new InlineArgumentsBlock(this.Emitter, argsInfo, inlineCode).Emit(); } else { if (String.IsNullOrEmpty(customCtor)) { this.WriteNew(); objectCreateExpression.Type.AcceptVisitor(this.Emitter); } else { this.Write(customCtor); } this.WriteOpenParentheses(); if (!isTypeParam && !this.Emitter.Validator.IsIgnoreType(type) && type.Methods.Count(m => m.IsConstructor && !m.IsStatic) > (type.IsValueType ? 0 : 1)) { this.WriteScript(OverloadsCollection.Create(this.Emitter, ((InvocationResolveResult)this.Emitter.Resolver.ResolveNode(objectCreateExpression, this.Emitter)).Member).GetOverloadName()); if (argsExpressions.Length > 0) { this.WriteComma(); } } new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg).Emit(); this.WriteCloseParentheses(); } if (hasInitializer) { this.WriteComma(); bool needComma = false; if (isCollectionInitializer) { this.Write("["); this.WriteNewLine(); this.Indent(); } else { this.BeginBlock(); } foreach (Expression item in elements) { if (needComma) { this.WriteComma(true); } needComma = true; if (item is NamedExpression) { var namedExpression = (NamedExpression)item; new NameBlock(this.Emitter, namedExpression.Name, namedExpression, namedExpression.Expression).Emit(); } else if (item is NamedArgumentExpression) { var namedArgumentExpression = (NamedArgumentExpression)item; new NameBlock(this.Emitter, namedArgumentExpression.Name, namedArgumentExpression, namedArgumentExpression.Expression).Emit(); } else if (item is ArrayInitializerExpression) { var arrayInitializer = (ArrayInitializerExpression)item; this.Write("["); foreach (var el in arrayInitializer.Elements) { this.EnsureComma(false); el.AcceptVisitor(this.Emitter); this.Emitter.Comma = true; } this.Write("]"); this.Emitter.Comma = false; } else if (item is IdentifierExpression) { var identifierExpression = (IdentifierExpression)item; new IdentifierBlock(this.Emitter, identifierExpression).Emit(); } } this.WriteNewLine(); if (isCollectionInitializer) { this.Outdent(); this.Write("]"); } else { this.EndBlock(); } this.WriteSpace(); this.WriteCloseParentheses(); } } Helpers.CheckValueTypeClone(invocationResolveResult, this.ObjectCreateExpression, this); }
public CilInstructionExpression() { Instructions = new List <CilInstruction>(); Arguments = new AstNodeCollection <CilExpression>(this); }
void AnalyzeExpression(AstNode expression, AstNode body, AstNodeCollection <ParameterDeclaration> parameters) { var invocation = AnalyzeBody(body); if (invocation == null) { return; } if (!IsSimpleTarget(invocation.Target)) { return; } var rr = ctx.Resolve(invocation) as CSharpInvocationResolveResult; if (rr == null) { return; } var lambdaParameters = parameters.ToList(); var arguments = rr.GetArgumentsForCall(); if (lambdaParameters.Count != arguments.Count) { return; } for (int i = 0; i < arguments.Count; i++) { var arg = UnpackImplicitIdentityOrReferenceConversion(arguments[i]) as LocalResolveResult; if (arg == null || arg.Variable.Name != lambdaParameters[i].Name) { return; } } var returnConv = ctx.GetConversion(invocation); if (returnConv.IsExplicit || !(returnConv.IsIdentityConversion || returnConv.IsReferenceConversion)) { return; } var validTypes = TypeGuessing.GetValidTypes(ctx.Resolver, expression).ToList(); // search for method group collisions var targetResult = ctx.Resolve(invocation.Target) as MethodGroupResolveResult; if (targetResult != null) { foreach (var t in validTypes) { if (t.Kind != TypeKind.Delegate) { continue; } var invokeMethod = t.GetDelegateInvokeMethod(); foreach (var otherMethod in targetResult.Methods) { if (otherMethod == rr.Member) { continue; } if (ParameterListComparer.Instance.Equals(otherMethod.Parameters, invokeMethod.Parameters)) { return; } } } } bool isValidReturnType = false; foreach (var t in validTypes) { if (t.Kind != TypeKind.Delegate) { continue; } var invokeMethod = t.GetDelegateInvokeMethod(); isValidReturnType = rr.Member.ReturnType == invokeMethod.ReturnType || rr.Member.ReturnType.GetAllBaseTypes().Contains(invokeMethod.ReturnType); if (isValidReturnType) { break; } } if (!isValidReturnType) { return; } AddIssue(new CodeIssue(expression, expression is AnonymousMethodExpression ? ctx.TranslateString("Anonymous method can be simplified to method group") : ctx.TranslateString("Lambda expression can be simplified to method group"), ctx.TranslateString("Replace with method group"), script => { if (validTypes.Any(t => t.FullName == "System.Func" && t.TypeParameterCount == 1 + parameters.Count) && validTypes.Any(t => t.FullName == "System.Action")) { if (rr != null && rr.Member.ReturnType.Kind != TypeKind.Void) { var builder = ctx.CreateTypeSystemAstBuilder(expression); var type = builder.ConvertType(new TopLevelTypeName("System", "Func", 1)); var args = type.GetChildrenByRole(Roles.TypeArgument); args.Clear(); foreach (var pde in parameters) { args.Add(builder.ConvertType(ctx.Resolve(pde).Type)); } args.Add(builder.ConvertType(rr.Member.ReturnType)); script.Replace(expression, new CastExpression(type, invocation.Target.Clone())); return; } } script.Replace(expression, invocation.Target.Clone()); })); }
protected AbstractMethodDeclaration() { Parameters = new AstNodeCollection<ParameterDeclaration>(this, AstNodeTitles.Parameter); }
public CilAstBlock() { Statements = new AstNodeCollection <CilStatement>(this); BlockHeader = new CilInstruction(CilOpCodes.Nop); }
void PrintInitializerElements(AstNodeCollection<Expression> elements, TokenRole open, TokenRole close) { // BraceStyle style; // if (policy.ArrayInitializerWrapping == Wrapping.WrapAlways) { // style = BraceStyle.NextLine; // } else { // style = BraceStyle.EndOfLine; // } WriteSpecialsUpToRole (open); WriteToken (open); formatter.Indent (); NewLine (); var col = 0; bool isFirst = true; foreach (AstNode node in elements) { if (isFirst) { isFirst = false; } else { Comma(node, noSpaceAfterComma: true); Space (); } col++; if ((col % 20) == 0) { NewLine (); } node.AcceptVisitor(this); } OptionalComma(); NewLine(); formatter.Unindent (); WriteSpecialsUpToRole (close); WriteToken (close); }
public ILAstBlock(Node cfgNode) { CfgNode = cfgNode ?? throw new ArgumentNullException(nameof(cfgNode)); Statements = new AstNodeCollection <ILStatement>(this); }
public static AstNodeCollection<ParameterDeclaration> ConvertToExternTypeParameters(AstNodeCollection<ParameterDeclaration> parameters) { foreach (ParameterDeclaration p in parameters) { if (Resolver.GetTypeName(p.Type).Equals("Array")) { if (p.Type is PtrType) { var ptr = p.Type as PtrType; if (ptr.Target is SimpleType) { SimpleType s = ptr.Target as SimpleType; if (s.TypeArguments.Any()) { p.Type = new PtrType((AstType)s.TypeArguments.ElementAt(0).Clone()); } } } } } return parameters; }
private IEnumerable <D.TypeParameter> GetTypeParameters(AstNodeCollection <TypeParameterDeclaration> typeParameters, AstNodeCollection <Constraint> constraints) { foreach (var p in typeParameters) { var gp = new D.TypeParameter(); gp.Name = p.Name; ITypeReference ct = null; foreach (var c in constraints) { if (c.TypeParameter.Identifier == p.Name) { foreach (var bt in c.BaseTypes) { var pt = bt as PrimitiveType; if (pt?.Keyword == "struct" || pt?.Keyword == "class" || pt?.Keyword == "new") { continue; } var nt = ResolveType(c, bt); if (ct == null) { ct = nt; } else if (ct is D.UnionType) { ((D.UnionType)ct).ElementTypes.Add(nt); } else { var ut = new D.UnionType(); ut.ElementTypes.Add(ct); ut.ElementTypes.Add(nt); ct = ut; } } } } gp.Constraint = ct; yield return(gp); } }
private void extractAttributes(AstNodeCollection<AttributeSection> attributes) { if (attributes != null) foreach (ICSharpCode.NRefactory.CSharp.AttributeSection a in attributes) { foreach (ICSharpCode.NRefactory.CSharp.Attribute at in a.Attributes) if (!this.attributes.Contains(at.FirstChild.ToString())) { this.attributes.Add(at.FirstChild.ToString()); } } }
void AnalyzeExpression(AstNode expression, AstNode body, AstNodeCollection <ParameterDeclaration> parameters) { var invocation = AnalyzeBody(body); if (invocation == null) { return; } if (!IsSimpleTarget(invocation.Target)) { return; } var rr = ctx.Resolve(invocation) as CSharpInvocationResolveResult; if (rr == null) { return; } var lambdaParameters = parameters.ToList(); var arguments = rr.GetArgumentsForCall(); if (lambdaParameters.Count != arguments.Count) { return; } for (int i = 0; i < arguments.Count; i++) { var arg = UnpackImplicitIdentityOrReferenceConversion(arguments[i]) as LocalResolveResult; if (arg == null || arg.Variable.Name != lambdaParameters[i].Name) { return; } } var returnConv = ctx.GetConversion(invocation); if (returnConv.IsExplicit || !(returnConv.IsIdentityConversion || returnConv.IsReferenceConversion)) { return; } AddIssue(expression, ctx.TranslateString("Expression can be reduced to delegate"), script => { var validTypes = CreateFieldAction.GetValidTypes(ctx.Resolver, expression).ToList(); if (validTypes.Any(t => t.FullName == "System.Func" && t.TypeParameterCount == 1 + parameters.Count) && validTypes.Any(t => t.FullName == "System.Action")) { if (rr != null && rr.Member.ReturnType.Kind != TypeKind.Void) { var builder = ctx.CreateTypeSytemAstBuilder(expression); var type = builder.ConvertType(new TopLevelTypeName("System", "Func", 1)); var args = type.GetChildrenByRole(Roles.TypeArgument); args.Clear(); foreach (var pde in parameters) { args.Add(builder.ConvertType(ctx.Resolve(pde).Type)); } args.Add(builder.ConvertType(rr.Member.ReturnType)); script.Replace(expression, new CastExpression(type, invocation.Target.Clone())); return; } } script.Replace(expression, invocation.Target.Clone()); }); }
void PrintInitializerElements(AstNodeCollection<Expression> elements) { BraceStyle style; if (policy.ArrayInitializerWrapping == Wrapping.WrapAlways) { style = BraceStyle.NextLine; } else { style = BraceStyle.EndOfLine; } OpenBrace(style); bool isFirst = true; foreach (AstNode node in elements) { if (isFirst) { isFirst = false; } else { Comma(node, noSpaceAfterComma: true); NewLine(); } node.AcceptVisitor(this); } OptionalComma(); NewLine(); CloseBrace(style); }
private void AddMethod(bool ctor, EntityDeclaration md, AstNodeCollection<ParameterDeclaration> ps) { ClassesAndStructsAndInterfaces csi = (ClassesAndStructsAndInterfaces)GetDeclarationFor(md); List<KeyValuePair<string, string>> args = ps.Select(p => new KeyValuePair<string, string>(p.Name, p.Type.ToString()) ) .ToList(); if( args.Count > 0 ){ args.ForEach(kvp => AddToNotDefaultReferencedTypes(csi, kvp.Value)); } Method m = new Method( GetVisibility(md), md.Name, al.CheckFlag(md.Modifiers, Modifiers.Static), al.CheckFlag(md.Modifiers, Modifiers.Virtual), al.CheckFlag(md.Modifiers, Modifiers.Abstract), al.CheckFlag(md.Modifiers, Modifiers.Override), md.ReturnType.ToString(), ctor, args ); AddToNotDefaultReferencedTypes(csi, m.ReturnType); csi.Methods.Add(m); }