public virtual PropertyDeclaration CreateProperty(IField field, bool createGetter, bool createSetter) { ClassFinder targetContext = new ClassFinder(field); string name = GetPropertyName(field.Name); PropertyDeclaration property = new PropertyDeclaration(ConvertModifier(field.Modifiers, targetContext), null, name, null); property.TypeReference = ConvertType(field.ReturnType, new ClassFinder(field)); if (createGetter) { BlockStatement block = new BlockStatement(); block.AddChild(new ReturnStatement(new IdentifierExpression(field.Name))); property.GetRegion = new PropertyGetRegion(block, null); } if (createSetter) { BlockStatement block = new BlockStatement(); Expression left = new IdentifierExpression(field.Name); Expression right = new IdentifierExpression("value"); block.AddChild(new ExpressionStatement(new AssignmentExpression(left, AssignmentOperatorType.Assign, right))); property.SetRegion = new PropertySetRegion(block, null); } property.Modifier = Modifiers.Public | (property.Modifier & Modifiers.Static); return(property); }
public static BlockStatement CreateNotImplementedBlock() { BlockStatement b = new BlockStatement(); b.AddChild(new ThrowStatement(new ObjectCreateExpression(new TypeReference("NotImplementedException"), null))); return(b); }
AbstractNode GenerateAstToInsert(string variableName) { var block = new BlockStatement(); // mark the place where to put caret block.AddChild(new ExpressionStatement(new IdentifierExpression(caretMarker))); return(new IfElseStatement( new BinaryOperatorExpression(new IdentifierExpression(variableName), BinaryOperatorType.InEquality, new PrimitiveExpression(null)), block)); }
private void WrapInBlock(IStatement statement) { if (statement == null || statement is BlockStatement) { return; } var block = new BlockStatement(statement.Context, new List <IStatement>()); statement.Parent.ReplaceChild(statement, block); block.AddChild(statement); }
void AddToBlock(VariableDeclaration hashCodeVar, MethodDeclaration getHashCodeMethod, bool usePrimeMultiplication, BlockStatement hashCalculationBlock, ref int fieldIndex, IProperty property) { Expression expr = new InvocationExpression(new MemberReferenceExpression(new IdentifierExpression(property.Name), "GetHashCode")); if (usePrimeMultiplication) { int prime = largePrimes[fieldIndex++ % largePrimes.Length]; expr = new AssignmentExpression(new IdentifierExpression(hashCodeVar.Name), AssignmentOperatorType.Add, new BinaryOperatorExpression(new PrimitiveExpression(prime, prime.ToString()), BinaryOperatorType.Multiply, expr)); } else { expr = new AssignmentExpression(new IdentifierExpression(hashCodeVar.Name), AssignmentOperatorType.ExclusiveOr, expr); } if (IsValueType(property.ReturnType)) { hashCalculationBlock.AddChild(new ExpressionStatement(expr)); } else { hashCalculationBlock.AddChild(new IfElseStatement(new BinaryOperatorExpression(new IdentifierExpression(property.Name), BinaryOperatorType.ReferenceInequality, new PrimitiveExpression(null, "null")), new ExpressionStatement(expr))); } }
public static void AddStatement(this BlockStatement block, Statement statement) { if (block == null) { throw new ArgumentNullException("block"); } if (statement == null) { throw new ArgumentNullException("statement"); } block.AddChild(statement); statement.Parent = block; }
public override object VisitForeachStatement(ForeachStatement foreachStatement, object data) { base.VisitForeachStatement(foreachStatement, data); FixTypeReferenceCasing(foreachStatement.TypeReference, foreachStatement.StartLocation); if (resolver.CompilationUnit == null) { return(null); } if (foreachStatement.TypeReference.IsNull) { ResolveResult rr = resolver.ResolveIdentifier(foreachStatement.VariableName, foreachStatement.StartLocation, ExpressionContext.Default); if (rr != null && rr.ResolvedType != null) { BlockStatement blockStatement = foreachStatement.EmbeddedStatement as BlockStatement; if (blockStatement == null) { blockStatement = new BlockStatement(); blockStatement.AddChild(foreachStatement.EmbeddedStatement); foreachStatement.EmbeddedStatement = blockStatement; } string newVariableName = foreachStatement.VariableName + "_loopVariable"; ExpressionStatement st = new ExpressionStatement( new AssignmentExpression( new IdentifierExpression(foreachStatement.VariableName), AssignmentOperatorType.Assign, new IdentifierExpression(newVariableName))); blockStatement.Children.Insert(0, st); st.Parent = blockStatement; foreachStatement.VariableName = newVariableName; foreachStatement.TypeReference = ConvertType(rr.ResolvedType); } } return(null); }
void AddBlockChildren (BlockStatement result, Block blockStatement, List<LocalInfo> localVariables, ref int curLocal) { foreach (Statement stmt in blockStatement.Statements) { if (stmt == null) continue; if (curLocal < localVariables.Count && IsLower (localVariables[curLocal].Location, stmt.loc)) { result.AddChild (CreateVariableDeclaration (localVariables[curLocal]), AbstractCSharpNode.Roles.Statement); curLocal++; } if (stmt is Block && !(stmt is ToplevelBlock || stmt is ExplicitBlock)) { AddBlockChildren (result, (Block)stmt, localVariables, ref curLocal); } else { result.AddChild ((INode)stmt.Accept (this), AbstractCSharpNode.Roles.Statement); } } }
public override object Visit (Block blockStatement) { if (blockStatement.IsGenerated) { if (blockStatement.Statements.First () is Using) return CreateUsingStatement (blockStatement); return blockStatement.Statements.Last ().Accept (this); } var result = new BlockStatement (); result.AddChild (new CSharpTokenNode (Convert (blockStatement.StartLocation), 1), AbstractCSharpNode.Roles.LBrace); int curLocal = 0; List<LocalInfo> localVariables = new List<LocalInfo> (blockStatement.Variables.Values); AddBlockChildren (result, blockStatement, localVariables, ref curLocal); while (curLocal < localVariables.Count) { result.AddChild (CreateVariableDeclaration (localVariables[curLocal]), AbstractCSharpNode.Roles.Statement); curLocal++; } result.AddChild (new CSharpTokenNode (Convert (blockStatement.EndLocation), 1), AbstractCSharpNode.Roles.RBrace); return result; }
public override object Visit(Block blockStatement) { if (blockStatement.IsCompilerGenerated && blockStatement.Statements.Any()) { if (blockStatement.Statements.First() is Using) return CreateUsingStatement(blockStatement); return blockStatement.Statements.Last().Accept(this); } var result = new BlockStatement(); result.AddChild(new CSharpTokenNode(Convert(blockStatement.StartLocation), Roles.LBrace), Roles.LBrace); int curLocal = 0; AddBlockChildren(result, blockStatement, ref curLocal); result.AddChild(new CSharpTokenNode(Convert(blockStatement.EndLocation), Roles.RBrace), Roles.RBrace); return result; }
void AddBlockChildren(BlockStatement result, Block blockStatement, ref int curLocal) { if (convertTypeSystemMode) { return; } foreach (Mono.CSharp.Statement stmt in blockStatement.Statements) { if (stmt == null) continue; /* if (curLocal < localVariables.Count && IsLower (localVariables[curLocal].Location, stmt.loc)) { result.AddChild (CreateVariableDeclaration (localVariables[curLocal]), Roles.Statement); curLocal++; }*/ if (stmt is Block && !(stmt is ToplevelBlock || stmt is ExplicitBlock)) { AddBlockChildren(result, (Block)stmt, ref curLocal); } else { result.AddChild((Statement)stmt.Accept(this), BlockStatement.StatementRole); } } }
private static void Main(string[] args) { var compilationUnit = new CompilationUnit(); var @namespace = new NamespaceDeclaration("NObjectiveAST"); compilationUnit.Children.Add(@namespace); var visitorsInterface = new TypeDeclaration(Modifiers.Public | Modifiers.Partial, null); visitorsInterface.Type = ClassType.Interface; visitorsInterface.Name = "IAstVisitor"; var traversalVisitor = new TypeDeclaration(Modifiers.Public | Modifiers.Partial, null); traversalVisitor.Type = ClassType.Class; traversalVisitor.Name = "TraversalVisitor"; traversalVisitor.BaseTypes = new List <TypeReference> { new TypeReference(visitorsInterface.Name) }; @namespace.Children.Add(visitorsInterface); @namespace.Children.Add(traversalVisitor); { var visitNode = new MethodDeclaration(); visitNode.Modifier = Modifiers.Public; visitNode.Name = "Visit"; visitNode.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("Node"), "node")); visitNode.TypeReference = new TypeReference("object"); visitNode.Body = new BlockStatement(); visitNode.Body.Children.Add(new ReturnStatement(new InvocationExpression(new MemberReferenceExpression(new IdentifierExpression("node"), "AcceptVisitor"), new List <Expression> { new ThisReferenceExpression() }))); traversalVisitor.Children.Add(visitNode); } foreach (var nodeType in Assembly.GetExecutingAssembly().GetTypes().Where(x => !x.IsAbstract && x.GetClassHierarchy().Contains(typeof(NObjectiveAST.Node))).OrderBy(x => x.Name)) { var visitMethod = new MethodDeclaration(); visitMethod.Name = "Visit"; visitMethod.Parameters.Add(new ParameterDeclarationExpression(new TypeReference(nodeType.Name), "node")); visitMethod.TypeReference = new TypeReference("object"); visitorsInterface.Children.Add(visitMethod); visitMethod = new MethodDeclaration(); visitMethod.Body = new BlockStatement(); visitMethod.Modifier = Modifiers.Public | Modifiers.Virtual; visitMethod.Name = "Visit"; visitMethod.Parameters.Add(new ParameterDeclarationExpression(new TypeReference(nodeType.Name), "node")); visitMethod.TypeReference = new TypeReference("object"); foreach (var astField in nodeType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Where(x => x.FieldType.GetClassHierarchy().Contains(typeof(NObjectiveAST.Node))).Where(x => x.Name != "Parent").OrderBy(x => x.Name)) { var block = new BlockStatement(); block.AddChild(new ExpressionStatement(new InvocationExpression(new IdentifierExpression("BeginVisit"), new List <Expression> { new PrimitiveExpression(GetPropertyName(astField.Name), GetPropertyName(astField.Name)), new MemberReferenceExpression(new IdentifierExpression("node"), GetPropertyName(astField.Name)) }))); block.AddChild(new ExpressionStatement(new InvocationExpression(new MemberReferenceExpression(new MemberReferenceExpression(new IdentifierExpression("node"), GetPropertyName(astField.Name)), "AcceptVisitor"), new List <Expression> { new ThisReferenceExpression() }))); block.AddChild(new ExpressionStatement(new InvocationExpression(new IdentifierExpression("EndVisit"), new List <Expression> { new PrimitiveExpression(GetPropertyName(astField.Name), GetPropertyName(astField.Name)), new MemberReferenceExpression(new IdentifierExpression("node"), GetPropertyName(astField.Name)) }))); visitMethod.Body.AddChild(new IfElseStatement(new BinaryOperatorExpression(new MemberReferenceExpression(new IdentifierExpression("node"), GetPropertyName(astField.Name)), BinaryOperatorType.InEquality, new PrimitiveExpression(null, "null")), block)); } foreach (var astField in nodeType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Where(x => x.FieldType.IsGenericType && x.FieldType.GetGenericTypeDefinition() == typeof(List <>) && x.FieldType.GetGenericArguments()[0].GetClassHierarchy().Contains(typeof(NObjectiveAST.Node))).OrderBy(x => x.Name)) { var block = new BlockStatement(); var foreachBlock = new BlockStatement(); foreachBlock.AddChild(new ExpressionStatement(new InvocationExpression(new IdentifierExpression("BeginVisit"), new List <Expression> { new PrimitiveExpression(GetPropertyName(astField.Name), GetPropertyName(astField.Name)), new IdentifierExpression("item") }))); foreachBlock.AddChild(new ExpressionStatement(new InvocationExpression(new MemberReferenceExpression(new IdentifierExpression("item"), "AcceptVisitor"), new List <Expression> { new ThisReferenceExpression() }))); foreachBlock.AddChild(new ExpressionStatement(new InvocationExpression(new IdentifierExpression("EndVisit"), new List <Expression> { new PrimitiveExpression(GetPropertyName(astField.Name), GetPropertyName(astField.Name)), new IdentifierExpression("item") }))); block.AddChild(new ExpressionStatement(new InvocationExpression(new IdentifierExpression("BeginVisitChildren"), new List <Expression> { new PrimitiveExpression(GetPropertyName(astField.Name), GetPropertyName(astField.Name)), new MemberReferenceExpression(new IdentifierExpression("node"), GetPropertyName(astField.Name)) }))); block.AddChild(new ForeachStatement(new TypeReference("var"), "item", new MemberReferenceExpression(new IdentifierExpression("node"), GetPropertyName(astField.Name)), foreachBlock)); block.AddChild(new ExpressionStatement(new InvocationExpression(new IdentifierExpression("EndVisitChildren"), new List <Expression> { new PrimitiveExpression(GetPropertyName(astField.Name), GetPropertyName(astField.Name)), new MemberReferenceExpression(new IdentifierExpression("node"), GetPropertyName(astField.Name)) }))); visitMethod.Body.AddChild(new IfElseStatement(new BinaryOperatorExpression(new MemberReferenceExpression(new IdentifierExpression("node"), GetPropertyName(astField.Name)), BinaryOperatorType.InEquality, new PrimitiveExpression(null, "null")), block)); } visitMethod.Body.Children.Add(new ReturnStatement(new PrimitiveExpression(null, "null"))); traversalVisitor.Children.Add(visitMethod); var astNodeExtension = new TypeDeclaration(Modifiers.Public, null); astNodeExtension.Type = ClassType.Class; astNodeExtension.Modifier |= Modifiers.Partial; astNodeExtension.Name = nodeType.Name; var acceptVisitor = new MethodDeclaration(); acceptVisitor.Modifier = Modifiers.Public | Modifiers.Override; acceptVisitor.Name = "AcceptVisitor"; acceptVisitor.Attributes.Add(new AttributeSection { Attributes = new List <ICSharpCode.NRefactory.Ast.Attribute> { new ICSharpCode.NRefactory.Ast.Attribute(typeof(DebuggerStepThroughAttribute).Name, null, null) } }); acceptVisitor.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("IAstVisitor"), "visitor")); acceptVisitor.TypeReference = new TypeReference("object"); acceptVisitor.Body = new BlockStatement(); acceptVisitor.Body.Children.Add(new ReturnStatement(new InvocationExpression(new MemberReferenceExpression(new IdentifierExpression("visitor"), "Visit"), new List <Expression> { new ThisReferenceExpression() }))); foreach (var item in nodeType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Where(x => x.Name.StartsWith("_"))) { var getBlock = new BlockStatement(); var setBlock = new BlockStatement(); getBlock.AddChild(new ReturnStatement(new IdentifierExpression(item.Name))); Expression assignment = new IdentifierExpression("value"); if (item.FieldType.GetClassHierarchy().Contains(typeof(NObjectiveAST.Node)) || (item.FieldType.IsGenericType && item.FieldType.GetGenericTypeDefinition() == typeof(List <>) && item.FieldType.GetGenericArguments()[0].GetClassHierarchy().Contains(typeof(NObjectiveAST.Node)))) { assignment = new InvocationExpression(new IdentifierExpression("SetParent"), new List <Expression> { assignment }); } setBlock.AddChild(new ExpressionStatement(new AssignmentExpression(new IdentifierExpression(item.Name), AssignmentOperatorType.Assign, assignment))); List <AttributeSection> attributes = null; if (item.FieldType.IsEnum || item.FieldType == typeof(string) || item.FieldType == typeof(int) || item.FieldType == typeof(uint) || item.FieldType == typeof(long) || item.FieldType == typeof(ulong) || item.FieldType == typeof(short) || item.FieldType == typeof(ushort) || item.FieldType == typeof(byte) || item.FieldType == typeof(sbyte) || item.FieldType == typeof(bool)) { attributes = new List <AttributeSection>(); attributes.Add(new AttributeSection { Attributes = new List <ICSharpCode.NRefactory.Ast.Attribute> { new ICSharpCode.NRefactory.Ast.Attribute() { Name = "XmlAttribute" } } }); } var property = new PropertyDeclaration(Modifiers.Public, attributes, GetPropertyName(item.Name), null); property.TypeReference = GetTypeReference(item.FieldType); property.GetRegion = new PropertyGetRegion(getBlock, null); property.SetRegion = new PropertySetRegion(setBlock, null); astNodeExtension.AddChild(property); } astNodeExtension.Children.Add(acceptVisitor); @namespace.Children.Add(astNodeExtension); } var outputVisitor = new CSharpOutputVisitor(); outputVisitor.VisitCompilationUnit(compilationUnit, null); //using( var writer ) File.WriteAllText(@"..\..\Visitors.Generated.cs", NObjectiveAST.Properties.Resources.FileHeader + outputVisitor.Text); }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { List <Change> result = new List <Change> (); MemberResolveResult resolveResult = options.ResolveResult as MemberResolveResult; IProperty property = resolveResult.ResolvedMember as IProperty; TextEditorData data = options.GetTextEditorData(); INRefactoryASTProvider astProvider = options.GetASTProvider(); backingStoreName = GetBackingStoreName(property); FieldDeclaration backingStore = new FieldDeclaration(null); backingStore.TypeReference = options.Document.CompilationUnit.ShortenTypeName(property.ReturnType, property.Location).ConvertToTypeReference(); backingStore.Fields.Add(new VariableDeclaration(backingStoreName)); DocumentLocation location = property.Location.ToDocumentLocation(data.Document); location.Column = 1; refactoringStartOffset = data.Document.LocationToOffset(location); result.Add(new TextReplaceChange() { FileName = options.Document.FileName, Offset = refactoringStartOffset, InsertedText = astProvider.OutputNode(options.Dom, backingStore, options.GetIndent(property)) }); if (property.HasGet) { int startOffset = data.Document.LocationToOffset(property.GetRegion.Start.ToDocumentLocation(data.Document)); int endOffset = data.Document.LocationToOffset(property.GetRegion.End.ToDocumentLocation(data.Document)); BlockStatement getBlock = new BlockStatement(); getBlock.AddChild(new ReturnStatement(new IdentifierExpression(backingStoreName))); string text = astProvider.OutputNode(options.Dom, new PropertyGetRegion(getBlock, null), options.GetIndent(property) + "\t").Trim(); result.Add(new TextReplaceChange() { FileName = options.Document.FileName, Offset = startOffset, RemovedChars = endOffset - startOffset, InsertedText = text }); } if (property.HasSet) { int startOffset = data.Document.LocationToOffset(property.SetRegion.Start.ToDocumentLocation(data.Document)); int endOffset = data.Document.LocationToOffset(property.SetRegion.End.ToDocumentLocation(data.Document)); BlockStatement setBlock = new BlockStatement(); setBlock.AddChild(new ExpressionStatement(new AssignmentExpression(new IdentifierExpression(backingStoreName), AssignmentOperatorType.Assign, new IdentifierExpression("value")))); string text = astProvider.OutputNode(options.Dom, new PropertySetRegion(setBlock, null), options.GetIndent(property) + "\t").Trim(); result.Add(new TextReplaceChange() { FileName = options.Document.FileName, Offset = startOffset, RemovedChars = endOffset - startOffset, InsertedText = text }); } return(result); }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { varCount = 0; selectionStart = selectionEnd = -1; List <Change> result = new List <Change> (); IResolver resolver = options.GetResolver(); INRefactoryASTProvider provider = options.GetASTProvider(); if (resolver == null || provider == null) { return(result); } TextEditorData data = options.GetTextEditorData(); if (data == null) { return(result); } ResolveResult resolveResult; LineSegment lineSegment; ICSharpCode.NRefactory.Ast.CompilationUnit unit = provider.ParseFile(data.Document.Text); MonoDevelop.Refactoring.ExtractMethod.VariableLookupVisitor visitor = new MonoDevelop.Refactoring.ExtractMethod.VariableLookupVisitor(resolver, new DomLocation(data.Caret.Line, data.Caret.Column)); if (options.ResolveResult == null) { LoggingService.LogError("resolve result == null:" + options.ResolveResult); return(result); } IMember callingMember = options.ResolveResult.CallingMember; if (callingMember != null) { visitor.MemberLocation = new Location(callingMember.Location.Column, callingMember.Location.Line); } unit.AcceptVisitor(visitor, null); if (data.IsSomethingSelected) { ExpressionResult expressionResult = new ExpressionResult(data.SelectedText.Trim()); if (expressionResult.Expression.Contains(" ") || expressionResult.Expression.Contains("\t")) { expressionResult.Expression = "(" + expressionResult.Expression + ")"; } resolveResult = resolver.Resolve(expressionResult, new DomLocation(data.Caret.Line, data.Caret.Column)); if (resolveResult == null) { return(result); } IReturnType resolvedType = resolveResult.ResolvedType; if (resolvedType == null || string.IsNullOrEmpty(resolvedType.Name)) { resolvedType = DomReturnType.Object; } varName = CreateVariableName(resolvedType, visitor); TypeReference returnType; if (resolveResult.ResolvedType == null || string.IsNullOrEmpty(resolveResult.ResolvedType.Name)) { returnType = new TypeReference("var"); returnType.IsKeyword = true; } else { returnType = options.ShortenTypeName(resolveResult.ResolvedType).ConvertToTypeReference(); } options.ParseMember(resolveResult.CallingMember); TextReplaceChange insert = new TextReplaceChange(); insert.FileName = options.Document.FileName; insert.Description = GettextCatalog.GetString("Insert variable declaration"); LocalVariableDeclaration varDecl = new LocalVariableDeclaration(returnType); varDecl.Variables.Add(new VariableDeclaration(varName, provider.ParseExpression(data.SelectedText))); GetContainingEmbeddedStatementVisitor blockVisitor = new GetContainingEmbeddedStatementVisitor(); blockVisitor.LookupLocation = new Location(data.Caret.Column + 1, data.Caret.Line + 1); unit.AcceptVisitor(blockVisitor, null); StatementWithEmbeddedStatement containing = blockVisitor.ContainingStatement as StatementWithEmbeddedStatement; if (containing != null && !(containing.EmbeddedStatement is BlockStatement)) { insert.Offset = data.Document.LocationToOffset(containing.StartLocation.Line - 1, containing.StartLocation.Column - 1); lineSegment = data.Document.GetLineByOffset(insert.Offset); insert.RemovedChars = data.Document.LocationToOffset(containing.EndLocation.Line - 1, containing.EndLocation.Column - 1) - insert.Offset; BlockStatement insertedBlock = new BlockStatement(); insertedBlock.AddChild(varDecl); insertedBlock.AddChild(containing.EmbeddedStatement); containing.EmbeddedStatement = insertedBlock; insert.InsertedText = provider.OutputNode(options.Dom, containing, options.GetWhitespaces(lineSegment.Offset)).TrimStart(); int offset, length; if (SearchSubExpression(insert.InsertedText, data.SelectedText, 0, out offset, out length)) { if (SearchSubExpression(insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) { insert.InsertedText = insert.InsertedText.Substring(0, offset) + varName + insert.InsertedText.Substring(offset + length); insertOffset = insert.Offset + offset; } } } else if (blockVisitor.ContainingStatement is IfElseStatement) { IfElseStatement ifElse = blockVisitor.ContainingStatement as IfElseStatement; insert.Offset = data.Document.LocationToOffset(blockVisitor.ContainingStatement.StartLocation.Line - 1, blockVisitor.ContainingStatement.StartLocation.Column - 1); lineSegment = data.Document.GetLineByOffset(insert.Offset); insert.RemovedChars = data.Document.LocationToOffset(blockVisitor.ContainingStatement.EndLocation.Line - 1, blockVisitor.ContainingStatement.EndLocation.Column - 1) - insert.Offset; BlockStatement insertedBlock = new BlockStatement(); insertedBlock.AddChild(varDecl); if (blockVisitor.ContainsLocation(ifElse.TrueStatement[0])) { insertedBlock.AddChild(ifElse.TrueStatement[0]); ifElse.TrueStatement[0] = insertedBlock; } else { insertedBlock.AddChild(ifElse.FalseStatement[0]); ifElse.FalseStatement[0] = insertedBlock; } insert.InsertedText = provider.OutputNode(options.Dom, blockVisitor.ContainingStatement, options.GetWhitespaces(lineSegment.Offset)); int offset, length; if (SearchSubExpression(insert.InsertedText, provider.OutputNode(options.Dom, insertedBlock), 0, out offset, out length)) { if (SearchSubExpression(insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) { if (SearchSubExpression(insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) { insert.InsertedText = insert.InsertedText.Substring(0, offset) + varName + insert.InsertedText.Substring(offset + length); insertOffset = insert.Offset + offset; } } } } else { lineSegment = data.Document.GetLine(data.Caret.Line); insert.Offset = lineSegment.Offset; insert.InsertedText = options.GetWhitespaces(lineSegment.Offset) + provider.OutputNode(options.Dom, varDecl) + Environment.NewLine; insertOffset = insert.Offset + options.GetWhitespaces(lineSegment.Offset).Length + provider.OutputNode(options.Dom, varDecl.TypeReference).Length + " ".Length; TextReplaceChange replace = new TextReplaceChange(); replace.FileName = options.Document.FileName; replace.Offset = data.SelectionRange.Offset; replace.RemovedChars = data.SelectionRange.Length; replace.InsertedText = varName; result.Add(replace); replaceOffset = replace.Offset; if (insert.Offset < replaceOffset) { replaceOffset += insert.InsertedText.Length - insert.RemovedChars; } varCount++; } result.Add(insert); varCount++; selectionStart = insert.Offset; return(result); } lineSegment = data.Document.GetLine(data.Caret.Line); string line = data.Document.GetTextAt(lineSegment); Expression expression = provider.ParseExpression(line); if (expression == null) { return(result); } resolveResult = resolver.Resolve(new ExpressionResult(line), new DomLocation(options.Document.TextEditor.CursorLine, options.Document.TextEditor.CursorColumn)); if (resolveResult.ResolvedType != null && !string.IsNullOrEmpty(resolveResult.ResolvedType.FullName)) { TextReplaceChange insert = new TextReplaceChange(); insert.FileName = options.Document.FileName; insert.Description = GettextCatalog.GetString("Insert variable declaration"); insert.Offset = lineSegment.Offset + options.GetWhitespaces(lineSegment.Offset).Length; varName = CreateVariableName(resolveResult.ResolvedType, visitor); LocalVariableDeclaration varDecl = new LocalVariableDeclaration(options.ShortenTypeName(resolveResult.ResolvedType).ConvertToTypeReference()); varDecl.Variables.Add(new VariableDeclaration(varName, expression)); insert.RemovedChars = expression.EndLocation.Column - 1; insert.InsertedText = provider.OutputNode(options.Dom, varDecl); insertOffset = insert.Offset + provider.OutputNode(options.Dom, varDecl.TypeReference).Length + " ".Length; result.Add(insert); varCount++; int idx = 0; while (idx < insert.InsertedText.Length - varName.Length) { if (insert.InsertedText.Substring(idx, varName.Length) == varName && (idx == 0 || insert.InsertedText[idx - 1] == ' ') && (idx == insert.InsertedText.Length - varName.Length - 1 || insert.InsertedText[idx + varName.Length] == ' ')) { selectionStart = insert.Offset + idx; selectionEnd = selectionStart + varName.Length; break; } idx++; } } return(result); }
protected override string GenerateCode(LanguageProperties language, IClass currentClass) { IDocumentLine line = editor.Document.GetLineForOffset(anchor.Offset); string indent = DocumentUtilitites.GetWhitespaceAfter(editor.Document, line.Offset); List <PropertyOrFieldWrapper> filtered = this.varList.SelectedItems.OfType <PropertyOrFieldWrapper>() .OrderBy(p => p.Index) .ToList(); BlockStatement block = new BlockStatement(); foreach (PropertyOrFieldWrapper w in filtered) { if (w.AddCheckForNull) { // true = reference, null = generic or unknown if (w.Type.IsReferenceType != false) { block.AddChild( new IfElseStatement( new BinaryOperatorExpression(new IdentifierExpression(w.ParameterName), BinaryOperatorType.Equality, new PrimitiveExpression(null)), new ThrowStatement(new ObjectCreateExpression(new TypeReference("ArgumentNullException"), new List <Expression>() { new PrimitiveExpression(w.ParameterName, '"' + w.ParameterName + '"') })) ) ); } else { block.AddChild( new IfElseStatement( new UnaryOperatorExpression(new MemberReferenceExpression(new IdentifierExpression(w.MemberName), "HasValue"), UnaryOperatorType.Not), new ThrowStatement(new ObjectCreateExpression(new TypeReference("ArgumentNullException"), new List <Expression>() { new PrimitiveExpression(w.ParameterName, '"' + w.ParameterName + '"') })) ) ); } } if (w.AddRangeCheck) { block.AddChild( new IfElseStatement( new BinaryOperatorExpression( new BinaryOperatorExpression(new IdentifierExpression(w.ParameterName), BinaryOperatorType.LessThan, new IdentifierExpression("lower")), BinaryOperatorType.LogicalOr, new BinaryOperatorExpression(new IdentifierExpression(w.ParameterName), BinaryOperatorType.GreaterThan, new IdentifierExpression("upper")) ), new ThrowStatement( new ObjectCreateExpression( new TypeReference("ArgumentOutOfRangeException"), new List <Expression>() { new PrimitiveExpression(w.ParameterName, '"' + w.ParameterName + '"'), new IdentifierExpression(w.ParameterName), new BinaryOperatorExpression(new PrimitiveExpression("Value must be between "), BinaryOperatorType.Concat, new BinaryOperatorExpression(new IdentifierExpression("lower"), BinaryOperatorType.Concat, new BinaryOperatorExpression(new PrimitiveExpression(" and "), BinaryOperatorType.Concat, new IdentifierExpression("upper")))) } ) ) ) ); } } foreach (PropertyOrFieldWrapper w in filtered) { block.AddChild(new ExpressionStatement(new AssignmentExpression(new MemberReferenceExpression(new ThisReferenceExpression(), w.MemberName), AssignmentOperatorType.Assign, new IdentifierExpression(w.ParameterName)))); } AnchorElement parameterListElement = context.ActiveElements .OfType <AnchorElement>() .FirstOrDefault(item => item.Name.Equals("parameterList", StringComparison.OrdinalIgnoreCase)); if (parameterListElement != null) { StringBuilder pList = new StringBuilder(); var parameters = filtered .Select(p => new ParameterDeclarationExpression(ConvertType(p.Type), p.ParameterName)) .ToList(); for (int i = 0; i < parameters.Count; i++) { if (i > 0) { pList.Append(", "); } pList.Append(language.CodeGenerator.GenerateCode(parameters[i], "")); } parameterListElement.Text = pList.ToString(); } StringBuilder builder = new StringBuilder(); foreach (var element in block.Children.OfType <AbstractNode>()) { builder.Append(language.CodeGenerator.GenerateCode(element, indent)); } return(builder.ToString().Trim()); }
public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); var ts = compilationUnit.Descendants.OfType<TypeDeclaration> ().Where (x => x.Members.Any (y => y.Name.EndsWith ("_cctor", StringComparison.Ordinal))).ToList (); if (ts.Count == 0) return; var p = ts [0].Parent; var b = new BlockStatement (); foreach (var t in ts) { var cctor = t.Members.First (y => y.Name.EndsWith ("_cctor", StringComparison.Ordinal)); b.AddChild (new ExpressionStatement (new InvocationExpression ( new MemberReferenceExpression (new TypeReferenceExpression (new SimpleType (t.Name)), cctor.Name) )), BlockStatement.StatementRole); } p.AddChild (b, SyntaxTree.MemberRole); }
/// <summary> /// Generates code that converts an object to the target type. /// </summary> public static Expression ConvertTo(string name, Expression value, TypeReference targetType, BlockStatement blockStatement, Statement failStmt, bool allowNull, bool isOptional, int seqNum) { if (Utility.IsType(targetType, "System.Object")) { // no conversion needed return(value); } string temp_local_name = String.Format("tmp{0}", seqNum); // create the "conversion failed" block ArrayList parameters = new ArrayList(); parameters.Add(value); parameters.Add(new PrimitiveExpression(targetType.Type, targetType.Type)); parameters.Add(new PrimitiveExpression(name, name)); // the statements to execute when the cast failed BlockStatement fail_block = new BlockStatement(); fail_block.AddChild(new StatementExpression(new InvocationExpression(new FieldReferenceExpression( new TypeReferenceExpression("PhpException"), "InvalidImplicitCast"), parameters))); fail_block.AddChild(failStmt); // try to determine whether the target type is a reference or value type Type system_type = Type.GetType(targetType.SystemType); if (system_type != null && system_type.IsValueType) { // value type LocalVariableDeclaration temp_local; if (isOptional) { temp_local = new LocalVariableDeclaration(targetType); temp_local.Variables.Add(new VariableDeclaration(temp_local_name)); blockStatement.AddChild(temp_local); BlockStatement new_block_stmt = new BlockStatement(); IfElseStatement opt_stmt = new IfElseStatement(new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new FieldReferenceExpression( new IdentifierExpression("Arg"), "Default")), new_block_stmt, new StatementExpression(new AssignmentExpression(new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, new ObjectCreateExpression(targetType, new ArrayList())))); blockStatement.AddChild(opt_stmt); blockStatement = new_block_stmt; } IfElseStatement if_stmt = new IfElseStatement(new UnaryOperatorExpression( new ParenthesizedExpression(new BinaryOperatorExpression(value, BinaryOperatorType.TypeCheck, new TypeReferenceExpression(targetType))), UnaryOperatorType.Not), fail_block); blockStatement.AddChild(if_stmt); if (isOptional) { blockStatement.AddChild(new StatementExpression(new AssignmentExpression( new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, new CastExpression(targetType, value)))); return(new IdentifierExpression(temp_local_name)); } else { return(new CastExpression(targetType, value)); } } else { // probably a reference type LocalVariableDeclaration temp_local = new LocalVariableDeclaration(targetType); blockStatement.AddChild(temp_local); if (isOptional) { // first check for Arg.Default temp_local.Variables.Add( new VariableDeclaration(temp_local_name, new PrimitiveExpression(null, String.Empty))); BlockStatement new_block_stmt = new BlockStatement(); IfElseStatement opt_stmt = new IfElseStatement(new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new FieldReferenceExpression( new IdentifierExpression("Arg"), "Default")), new_block_stmt); blockStatement.AddChild(opt_stmt); blockStatement = new_block_stmt; // then perform the as-cast blockStatement.AddChild(new StatementExpression(new AssignmentExpression( new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, CreateAsCastExpression(value, targetType)))); } else { // perform the as-cast temp_local.Variables.Add( new VariableDeclaration(temp_local_name, CreateAsCastExpression(value, targetType))); } IfElseStatement if_stmt = new IfElseStatement(new BinaryOperatorExpression( new IdentifierExpression(temp_local_name), BinaryOperatorType.Equality, new PrimitiveExpression(null, String.Empty)), fail_block); if (allowNull) { // throw only if the value is not of targetType and not null if_stmt.Condition = new BinaryOperatorExpression(if_stmt.Condition, BinaryOperatorType.LogicalAnd, new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new PrimitiveExpression(null, String.Empty))); } blockStatement.AddChild(if_stmt); return(new IdentifierExpression(temp_local_name)); } }
/// <summary> /// Generates code that converts an object to the target type. /// </summary> public static Expression ConvertTo(string name, Expression value, TypeReference targetType, BlockStatement blockStatement, Statement failStmt, bool allowNull, bool isOptional, int seqNum) { if (Utility.IsType(targetType, "System.Object")) { // no conversion needed return value; } string temp_local_name = String.Format("tmp{0}", seqNum); // create the "conversion failed" block ArrayList parameters = new ArrayList(); parameters.Add(value); parameters.Add(new PrimitiveExpression(targetType.Type, targetType.Type)); parameters.Add(new PrimitiveExpression(name, name)); // the statements to execute when the cast failed BlockStatement fail_block = new BlockStatement(); fail_block.AddChild(new StatementExpression(new InvocationExpression(new FieldReferenceExpression( new TypeReferenceExpression("PhpException"), "InvalidImplicitCast"), parameters))); fail_block.AddChild(failStmt); // try to determine whether the target type is a reference or value type Type system_type = Type.GetType(targetType.SystemType); if (system_type != null && system_type.IsValueType) { // value type LocalVariableDeclaration temp_local; if (isOptional) { temp_local = new LocalVariableDeclaration(targetType); temp_local.Variables.Add(new VariableDeclaration(temp_local_name)); blockStatement.AddChild(temp_local); BlockStatement new_block_stmt = new BlockStatement(); IfElseStatement opt_stmt = new IfElseStatement(new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new FieldReferenceExpression( new IdentifierExpression("Arg"), "Default")), new_block_stmt, new StatementExpression(new AssignmentExpression(new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, new ObjectCreateExpression(targetType, new ArrayList())))); blockStatement.AddChild(opt_stmt); blockStatement = new_block_stmt; } IfElseStatement if_stmt = new IfElseStatement(new UnaryOperatorExpression( new ParenthesizedExpression(new BinaryOperatorExpression(value, BinaryOperatorType.TypeCheck, new TypeReferenceExpression(targetType))), UnaryOperatorType.Not), fail_block); blockStatement.AddChild(if_stmt); if (isOptional) { blockStatement.AddChild(new StatementExpression(new AssignmentExpression( new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, new CastExpression(targetType, value)))); return new IdentifierExpression(temp_local_name); } else return new CastExpression(targetType, value); } else { // probably a reference type LocalVariableDeclaration temp_local = new LocalVariableDeclaration(targetType); blockStatement.AddChild(temp_local); if (isOptional) { // first check for Arg.Default temp_local.Variables.Add( new VariableDeclaration(temp_local_name, new PrimitiveExpression(null, String.Empty))); BlockStatement new_block_stmt = new BlockStatement(); IfElseStatement opt_stmt = new IfElseStatement(new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new FieldReferenceExpression( new IdentifierExpression("Arg"), "Default")), new_block_stmt); blockStatement.AddChild(opt_stmt); blockStatement = new_block_stmt; // then perform the as-cast blockStatement.AddChild(new StatementExpression(new AssignmentExpression( new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, CreateAsCastExpression(value, targetType)))); } else { // perform the as-cast temp_local.Variables.Add( new VariableDeclaration(temp_local_name, CreateAsCastExpression(value, targetType))); } IfElseStatement if_stmt = new IfElseStatement(new BinaryOperatorExpression( new IdentifierExpression(temp_local_name), BinaryOperatorType.Equality, new PrimitiveExpression(null, String.Empty)), fail_block); if (allowNull) { // throw only if the value is not of targetType and not null if_stmt.Condition = new BinaryOperatorExpression(if_stmt.Condition, BinaryOperatorType.LogicalAnd, new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new PrimitiveExpression(null, String.Empty))); } blockStatement.AddChild(if_stmt); return new IdentifierExpression(temp_local_name); } }
protected override IEnumerable <string> GenerateCode(INRefactoryASTProvider astProvider, string indent, List <IBaseMember> includedMembers) { // Genereate Equals MethodDeclaration methodDeclaration = new MethodDeclaration(); methodDeclaration.Name = "Equals"; methodDeclaration.TypeReference = DomReturnType.Bool.ConvertToTypeReference(); methodDeclaration.Modifier = ICSharpCode.NRefactory.Ast.Modifiers.Public | ICSharpCode.NRefactory.Ast.Modifiers.Override; methodDeclaration.Body = new BlockStatement(); methodDeclaration.Parameters.Add(new ParameterDeclarationExpression(DomReturnType.Object.ConvertToTypeReference(), "obj")); IdentifierExpression paramId = new IdentifierExpression("obj"); IfElseStatement ifStatement = new IfElseStatement(null); ifStatement.Condition = new BinaryOperatorExpression(paramId, BinaryOperatorType.Equality, new PrimitiveExpression(null)); ifStatement.TrueStatement.Add(new ReturnStatement(new PrimitiveExpression(false))); methodDeclaration.Body.AddChild(ifStatement); ifStatement = new IfElseStatement(null); List <Expression> arguments = new List <Expression> (); arguments.Add(new ThisReferenceExpression()); arguments.Add(paramId); ifStatement.Condition = new InvocationExpression(new IdentifierExpression("ReferenceEquals"), arguments); ifStatement.TrueStatement.Add(new ReturnStatement(new PrimitiveExpression(true))); methodDeclaration.Body.AddChild(ifStatement); ifStatement = new IfElseStatement(null); ifStatement.Condition = new BinaryOperatorExpression(new InvocationExpression(new MemberReferenceExpression(paramId, "GetType")), BinaryOperatorType.InEquality, new TypeOfExpression(new TypeReference(Options.EnclosingType.Name))); ifStatement.TrueStatement.Add(new ReturnStatement(new PrimitiveExpression(false))); methodDeclaration.Body.AddChild(ifStatement); LocalVariableDeclaration varDecl = new LocalVariableDeclaration(new DomReturnType(Options.EnclosingType).ConvertToTypeReference()); varDecl.Variables.Add(new VariableDeclaration("other", new CastExpression(varDecl.TypeReference, paramId, CastType.Cast))); methodDeclaration.Body.AddChild(varDecl); IdentifierExpression otherId = new IdentifierExpression("other"); Expression binOp = null; foreach (IMember member in includedMembers) { Expression right = new BinaryOperatorExpression(new IdentifierExpression(member.Name), BinaryOperatorType.Equality, new MemberReferenceExpression(otherId, member.Name)); if (binOp == null) { binOp = right; } else { binOp = new BinaryOperatorExpression(binOp, BinaryOperatorType.LogicalAnd, right); } } methodDeclaration.Body.AddChild(new ReturnStatement(binOp)); yield return(astProvider.OutputNode(this.Options.Dom, methodDeclaration, indent)); methodDeclaration = new MethodDeclaration(); methodDeclaration.Name = "GetHashCode"; methodDeclaration.TypeReference = DomReturnType.Int32.ConvertToTypeReference(); methodDeclaration.Modifier = ICSharpCode.NRefactory.Ast.Modifiers.Public | ICSharpCode.NRefactory.Ast.Modifiers.Override; methodDeclaration.Body = new BlockStatement(); binOp = null; foreach (IMember member in includedMembers) { Expression right; right = new InvocationExpression(new MemberReferenceExpression(new IdentifierExpression(member.Name), "GetHashCode")); IType type = Options.Dom.SearchType(member, member.ReturnType); if (type != null && type.ClassType != MonoDevelop.Projects.Dom.ClassType.Struct && type.ClassType != MonoDevelop.Projects.Dom.ClassType.Enum) { right = new ParenthesizedExpression(new ConditionalExpression(new BinaryOperatorExpression(new IdentifierExpression(member.Name), BinaryOperatorType.InEquality, new PrimitiveExpression(null)), right, new PrimitiveExpression(0))); } if (binOp == null) { binOp = right; } else { binOp = new BinaryOperatorExpression(binOp, BinaryOperatorType.ExclusiveOr, right); } } BlockStatement uncheckedBlock = new BlockStatement(); uncheckedBlock.AddChild(new ReturnStatement(binOp)); methodDeclaration.Body.AddChild(new UncheckedStatement(uncheckedBlock)); yield return(astProvider.OutputNode(this.Options.Dom, methodDeclaration, indent)); }