public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
		{
			base.VisitCompilationUnit(compilationUnit, data);
			if (!string.IsNullOrEmpty(NamespacePrefixToAdd)) {
				for (int i = 0; i < compilationUnit.Children.Count; i++) {
					NamespaceDeclaration ns = compilationUnit.Children[i] as NamespaceDeclaration;
					if (ns != null) {
						ns.Name = NamespacePrefixToAdd + "." + ns.Name;
					}
					if (compilationUnit.Children[i] is TypeDeclaration || compilationUnit.Children[i] is DelegateDeclaration) {
						ns = new NamespaceDeclaration(NamespacePrefixToAdd);
						ns.AddChild(compilationUnit.Children[i]);
						compilationUnit.Children[i] = ns;
					}
				}
			}
			
			ToCSharpConvertVisitor v = new ToCSharpConvertVisitor();
			compilationUnit.AcceptVisitor(v, data);
			if (projectContent != null && projectContent.DefaultImports != null) {
				int index = 0;
				foreach (string u in projectContent.DefaultImports.Usings) {
					compilationUnit.Children.Insert(index++, new UsingDeclaration(u));
				}
			}
			return null;
		}
		public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
		{
			base.VisitCompilationUnit(compilationUnit, data);
			ToVBNetConvertVisitor v = new ToVBNetConvertVisitor();
			compilationUnit.AcceptVisitor(v, data);
			return null;
		}
Пример #3
0
		public static string GenerateText(TypeDeclaration type, OrderedPartCollection<AbstractDynamicCompilationExtension> extensions)
		{
			var unit = new CompilationUnit();

			var namespaces = new HashSet<string>
			{
				typeof (SystemTime).Namespace,
				typeof (AbstractViewGenerator).Namespace,
				typeof (Enumerable).Namespace,
				typeof (IEnumerable<>).Namespace,
				typeof (IEnumerable).Namespace,
				typeof (int).Namespace,
				typeof (LinqOnDynamic).Namespace,
				typeof(Field).Namespace,
			};
			foreach (var extension in extensions)
			{
				foreach (var ns in extension.Value.GetNamespacesToImport())
				{
					namespaces.Add(ns);
				}
			}

			foreach (var ns in namespaces)
			{
				unit.AddChild(new Using(ns));
			}

			unit.AddChild(type);
			var output = new CSharpOutputVisitor();
			unit.AcceptVisitor(output, null);

			return output.Text;
		}
        string RetrieveBackingStore(MonoDevelop.Refactoring.RefactoringOptions options, MonoDevelop.Refactoring.INRefactoryASTProvider astProvider, MonoDevelop.Projects.Dom.IProperty property)
        {
            ICSharpCode.NRefactory.Ast.CompilationUnit compilationUnit = astProvider.ParseFile(options.Document.TextEditor.Text);
            PropertyVisitor visitor = new PropertyVisitor(property);

            compilationUnit.AcceptVisitor(visitor, null);
            return(visitor.BackingStoreName);
        }
Пример #5
0
 public void rewriteCode_CSharp(CompilationUnit unit, IList<ISpecial> specials)
 {        	
     var outputVisitor  = new CSharpOutputVisitor();    		
     using (SpecialNodesInserter.Install(specials, outputVisitor)) {
         unit.AcceptVisitor(outputVisitor, null);
     }
     //codeTextBox.Text = outputVisitor.Text.Replace("\t", "  ");
     CSharpCode = outputVisitor.Text;
 }
		protected override void ConvertAst(CompilationUnit compilationUnit, List<ISpecial> specials, FileProjectItem sourceItem)
		{
			PreprocessingDirective.CSharpToVB(specials);
			IProjectContent pc = ParserService.GetProjectContent(sourceItem.Project) ?? ParserService.CurrentProjectContent;
			CSharpToVBNetConvertVisitor visitor = new CSharpToVBNetConvertVisitor(pc, ParserService.GetParseInformation(sourceItem.FileName));
			visitor.RootNamespaceToRemove = sourceItem.Project.RootNamespace;
			visitor.DefaultImportsToRemove = defaultImports;
			visitor.StartupObjectToMakePublic = startupObject;
			compilationUnit.AcceptVisitor(visitor, null);
		}
		protected override void ConvertAst(CompilationUnit compilationUnit, List<ISpecial> specials, FileProjectItem sourceItem)
		{
			PreprocessingDirective.VBToCSharp(specials);
			CompilableProject project = (CompilableProject)sourceItem.Project;
			RemoveWindowsFormsSpecificCode(compilationUnit, specials, project.OutputType == OutputType.WinExe);
			
			IProjectContent pc = ParserService.GetProjectContent(sourceItem.Project) ?? ParserService.CurrentProjectContent;
			VBNetToCSharpConvertVisitor visitor = new VBNetToCSharpConvertVisitorWithMyFormsSupport(pc, ParserService.GetParseInformation(sourceItem.FileName), sourceItem.Project.RootNamespace);
			compilationUnit.AcceptVisitor(visitor, null);
		}
 public ICompilationUnit setCurrentCompilationUnit(CompilationUnit compilationUnit)
 {
     if (compilationUnit == null)
         return null;
     NRefactoryASTConvertVisitor converter;
     converter = new NRefactoryASTConvertVisitor(myProjectContent);
     compilationUnit.AcceptVisitor(converter, null);
     var newCompilationUnit = converter.Cu;
     parseInformation.SetCompilationUnit(newCompilationUnit);
     return newCompilationUnit;            
 }
Пример #9
0
        public void rewriteCode_VBNet(CompilationUnit unit, IList<ISpecial> specials)
        {
            var outputVisitor  = new VBNetOutputVisitor();
            using (SpecialNodesInserter.Install(specials, outputVisitor)) {
                unit.AcceptVisitor(outputVisitor, null);
            }
            //codeTextBox.Text = outputVisitor.Text.Replace("\t", "  ");
            VBNetCode = outputVisitor.Text;

            //    		PublicDI.log.debug(recreatedCode);
        }
Пример #10
0
    //DC
 /*   public void loadCode(string code)
    { 
        code = (code.fileExists()) ? code.fileContents() : code;
        var parser = code.csharpAst();
        loadCompilationUnit(parser.CompilationUnit);
    }*/
    //DC
    public void loadCompilationUnit(CompilationUnit compilationUnit)
    {
        try
        {
            compilationUnit.AcceptVisitor(this, null);
        }
        catch (Exception ex)
        {
            ex.log("in MapAstToDom loadCompilationUnit");
        }
    }
Пример #11
0
 public static Module Convert(NR.CompilationUnit cu, ConverterSettings settings)
 {
     if (cu == null)
     {
         throw new ArgumentNullException("cu");
     }
     if (settings == null)
     {
         throw new ArgumentNullException("settings");
     }
     if (settings.IsVisualBasic)
     {
         cu.AcceptVisitor(new VBNetConstructsConvertVisitor {
             AddDefaultValueInitializerToLocalVariableDeclarations = false
         }, null);
     }
     else
     {
         cu.AcceptVisitor(new CSharpConstructsConvertVisitor(), null);
     }
     return((Module)cu.AcceptVisitor(new ConvertVisitor(settings), null));
 }
Пример #12
0
        public static string GenerateText(TypeDeclaration type)
        {
            var unit = new CompilationUnit();
            unit.AddChild(new Using(typeof (AbstractViewGenerator).Namespace));
            unit.AddChild(new Using(typeof (Enumerable).Namespace));
            unit.AddChild(new Using(typeof (int).Namespace));
            unit.AddChild(new Using(typeof (LinqOnDynamic).Namespace));
            unit.AddChild(type);

            var output = new CSharpOutputVisitor();
            unit.AcceptVisitor(output, null);

            return output.Text;
        }
		protected override void ConvertAst(CompilationUnit compilationUnit, List<ISpecial> specials, FileProjectItem sourceItem)
		{
			PreprocessingDirective.VBToCSharp(specials);
			CompilableProject project = (CompilableProject)sourceItem.Project;
			RemoveWindowsFormsSpecificCode(compilationUnit, specials, project.OutputType == OutputType.WinExe);
			
			IProjectContent pc = ParserService.GetProjectContent(sourceItem.Project) ?? ParserService.CurrentProjectContent;
			VBNetToCSharpConvertVisitor visitor = new VBNetToCSharpConvertVisitorWithMyFormsSupport(pc, ParserService.GetParseInformation(sourceItem.FileName), sourceItem.Project.RootNamespace);
						
			// set project options
			visitor.OptionInfer = (project.GetEvaluatedProperty("OptionInfer") ?? "Off")
				.Equals("On", StringComparison.OrdinalIgnoreCase);
			visitor.OptionStrict = (project.GetEvaluatedProperty("OptionStrict") ?? "Off")
				.Equals("On", StringComparison.OrdinalIgnoreCase);
			
			compilationUnit.AcceptVisitor(visitor, null);
		}
Пример #14
0
		private ICompilationUnit ConvertCompilationUnit(CompilationUnit cu)
		{
			var supportedLanguage = SupportedLanguage == SupportedLanguage.CSharp
				? ICSharpCode.NRefactory.SupportedLanguage.CSharp
				: ICSharpCode.NRefactory.SupportedLanguage.VBNet;
			var converter = new NRefactoryASTConvertVisitor(ProjectContent, supportedLanguage);
			cu.AcceptVisitor(converter, null);
			return converter.Cu;
		}
		public static ResolveResult ResolveLowLevel(string fileName, string fileContent, int caretLine, int caretColumn, CompilationUnit compilationUnit, string expressionString, Expression expression, ExpressionContext context)
		{
			if (fileName == null) {
				throw new ArgumentNullException("fileName");
			}
			if (fileContent == null) {
				throw new ArgumentNullException("fileName");
			}
			if (expression == null) {
				throw new ArgumentNullException("expression");
			}
			
			IProject p = ProjectFileDictionaryService.GetProjectForFile(fileName);
			if (p == null) {
				LoggingService.Info("ResourceToolkit: NRefactoryAstCacheService: ResolveLowLevel failed. Project is null for file '"+fileName+"'");
				return null;
			}
			
			IProjectContent pc = ResourceResolverService.GetProjectContent(p);
			if (pc == null) {
				LoggingService.Info("ResourceToolkit: NRefactoryAstCacheService: ResolveLowLevel failed. ProjectContent is null for project '"+p.ToString()+"'");
				return null;
			}
			
			NRefactoryResolver resolver = ResourceResolverService.CreateResolver(fileName) as NRefactoryResolver;
			if (resolver == null) {
				resolver = new NRefactoryResolver(LanguageProperties.CSharp);
			}
			
			if (compilationUnit == null) {
				compilationUnit = GetFullAst(resolver.Language, fileName, fileContent);
			}
			if (compilationUnit == null) {
				LoggingService.Info("ResourceToolkit: NRefactoryAstCacheService: ResolveLowLevel failed due to the compilation unit being unavailable.");
				return null;
			}
			
			if (!resolver.Initialize(ParserService.GetParseInformation(fileName), caretLine, caretColumn)) {
				LoggingService.Info("ResourceToolkit: NRefactoryAstCacheService: ResolveLowLevel failed. NRefactoryResolver.Initialize returned false.");
				return null;
			}
			
			if (resolver.CallingClass != null) {
				ResolveResult rr;
				if (expressionString == null) {
					// HACK: Re-generate the code for the expression from the expression object by using the code generator.
					// This is necessary when invoking from inside an AST visitor where the
					// code belonging to this expression is unavailable.
					expressionString = resolver.LanguageProperties.CodeGenerator.GenerateCode(expression, String.Empty);
				}
				if ((rr = CtrlSpaceResolveHelper.GetResultFromDeclarationLine(resolver.CallingClass, resolver.CallingMember as IMethodOrProperty, caretLine, caretColumn, new ExpressionResult(expressionString))) != null) {
					return rr;
				}
			}
			
			if (resolver.CallingMember != null) {
				
				// Cache member->node mappings to improve performance
				// (if cache is enabled)
				INode memberNode;
				if (!CacheEnabled || !cachedMemberMappings.TryGetValue(resolver.CallingMember, out memberNode)) {
					MemberFindAstVisitor visitor = new MemberFindAstVisitor(resolver.CallingMember);
					compilationUnit.AcceptVisitor(visitor, null);
					memberNode = visitor.MemberNode;
					if (CacheEnabled && memberNode != null) {
						cachedMemberMappings.Add(resolver.CallingMember, memberNode);
					}
				}
				
				if (memberNode == null) {
					LoggingService.Info("ResourceToolkit: NRefactoryAstCacheService: Could not find member in AST: "+resolver.CallingMember.ToString());
				} else {
					resolver.RunLookupTableVisitor(memberNode);
				}
				
			}
			
			return resolver.ResolveInternal(expression, context);
		}
		void RemoveWindowsFormsSpecificCode(CompilationUnit compilationUnit, List<ISpecial> specials, bool keepCode)
		{
			for (int i = 0; i < specials.Count; i++) {
				PreprocessingDirective ppd = specials[i] as PreprocessingDirective;
				if (ppd != null && ppd.Cmd == "#if") {
					if (ppd.Arg == "_MyType = \"WindowsForms\"") {
						int depth = 1;
						for (int j = i + 1; j < specials.Count; j++) {
							ppd = specials[j] as PreprocessingDirective;
							if (ppd != null) {
								if (ppd.Cmd == "#if") {
									depth++;
								} else if (ppd.Cmd == "#endif") {
									depth--;
									if (depth == 0) {
										if (keepCode) {
											// keep code, remove only the ifdef
											specials.RemoveAt(j);
											specials.RemoveAt(i);
										} else {
											// remove ifdef including the code
											compilationUnit.AcceptVisitor(new RemoveMembersInRangeVisitor(
												DomRegion.FromLocation(specials[i].StartPosition, specials[j].EndPosition)), null);
											specials.RemoveRange(i, j - i + 1);
										}
										i--;
										break;
									}
								}
							}
						}
					}
				}
			}
		}
Пример #17
0
        public override List <Change> PerformChanges(RefactoringOptions options, object properties)
        {
            List <Change> result = new List <Change> ();
            IType         type   = options.SelectedItem as IType;

            if (type == null)
            {
                return(result);
            }
            string newName = GetCorrectFileName(type);

            if (type.CompilationUnit.Types.Count == 1)
            {
                result.Add(new RenameFileChange(type.CompilationUnit.FileName, newName));
            }
            else
            {
                StringBuilder content = new StringBuilder();

                if (options.Dom.Project is DotNetProject)
                {
                    content.Append(StandardHeaderService.GetHeader(options.Dom.Project, newName, true) + Environment.NewLine);
                }

                INRefactoryASTProvider                     provider = options.GetASTProvider();
                Mono.TextEditor.TextEditorData             data     = options.GetTextEditorData();
                ICSharpCode.NRefactory.Ast.CompilationUnit unit     = provider.ParseFile(options.Document.Editor.Text);

                TypeFilterTransformer typeFilterTransformer = new TypeFilterTransformer((type is InstantiatedType) ? ((InstantiatedType)type).UninstantiatedType.DecoratedFullName : type.DecoratedFullName);
                unit.AcceptVisitor(typeFilterTransformer, null);
                if (typeFilterTransformer.TypeDeclaration == null)
                {
                    return(result);
                }
                Mono.TextEditor.Document generatedDocument = new Mono.TextEditor.Document();
                generatedDocument.Text = provider.OutputNode(options.Dom, unit);

                int startLine = 0;
                int minLine   = typeFilterTransformer.TypeDeclaration.StartLocation.Line;
                foreach (var attr in typeFilterTransformer.TypeDeclaration.Attributes)
                {
                    minLine = Math.Min(minLine, attr.StartLocation.Line);
                }
                for (int i = minLine - 1; i >= 1; i--)
                {
                    string lineText = data.Document.GetTextAt(data.Document.GetLine(i)).Trim();
                    if (string.IsNullOrEmpty(lineText))
                    {
                        continue;
                    }
                    if (lineText.StartsWith("///"))
                    {
                        startLine = i;
                    }
                    else
                    {
                        break;
                    }
                }

                int start;
                if (startLine >= 1)
                {
                    start = data.Document.GetLine(startLine).Offset;
                }
                else
                {
                    var startLocation = typeFilterTransformer.TypeDeclaration.StartLocation;
                    startLocation.Column = 1;
                    foreach (var attr in typeFilterTransformer.TypeDeclaration.Attributes)
                    {
                        if (attr.StartLocation < startLocation)
                        {
                            startLocation = attr.StartLocation;
                        }
                    }

                    start = data.Document.LocationToOffset(startLocation.Line, 1);
                }
                int length = data.Document.LocationToOffset(typeFilterTransformer.TypeDeclaration.EndLocation.Line, typeFilterTransformer.TypeDeclaration.EndLocation.Column) - start;

                ICSharpCode.NRefactory.Ast.CompilationUnit generatedCompilationUnit = provider.ParseFile(generatedDocument.Text);
                TypeSearchVisitor typeSearchVisitor = new TypeSearchVisitor();
                generatedCompilationUnit.AcceptVisitor(typeSearchVisitor, null);

                int genStart = generatedDocument.LocationToOffset(typeSearchVisitor.Types[0].StartLocation.Line, 0);
                foreach (var attr in typeSearchVisitor.Types[0].Attributes)
                {
                    genStart = Math.Min(genStart, generatedDocument.LocationToOffset(attr.StartLocation.Line, 0));
                }

                int genEnd = generatedDocument.LocationToOffset(typeSearchVisitor.Types[0].EndLocation.Line, typeSearchVisitor.Types[0].EndLocation.Column);
                ((Mono.TextEditor.IBuffer)generatedDocument).Replace(genStart, genEnd - genStart, data.Document.GetTextAt(start, length));
                content.Append(generatedDocument.Text);

                result.Add(new CreateFileChange(newName, content.ToString()));

                TextReplaceChange removeDeclaration = new TextReplaceChange();
                removeDeclaration.Description  = "Remove type declaration";
                removeDeclaration.FileName     = type.CompilationUnit.FileName;
                removeDeclaration.Offset       = start;
                removeDeclaration.RemovedChars = length;
                result.Add(removeDeclaration);
            }
            result.Add(new SaveProjectChange(options.Document.Project));

            return(result);
        }
Пример #18
0
		public void ComplexExample()
		{
			string code = @"class A {
	Button closeButton;
	void M() {
		System.Windows.Forms.Panel panel1;
		closeButton = new System.Windows.Forms.Button();
		panel1 = new System.Windows.Forms.Panel();
		panel1.SuspendLayout();
		panel1.Controls.Add(this.closeButton);
		closeButton.BackColor = System.Drawing.Color.FromArgb();
		panel1.BackColor = System.Drawing.SystemColors.Info;
	}
}";
			TypeDeclaration decl = Ast.ParseUtilCSharp.ParseGlobal<TypeDeclaration>(code);
			CompilationUnit cu = new CompilationUnit();
			cu.AddChild(decl);
			CodeNamespace ns = (CodeNamespace)cu.AcceptVisitor(new CodeDomVisitor(), null);
			Assert.AreEqual("A", ns.Types[0].Name);
			Assert.AreEqual("closeButton", ns.Types[0].Members[0].Name);
			Assert.AreEqual("M", ns.Types[0].Members[1].Name);
			CodeMemberMethod m = (CodeMemberMethod)ns.Types[0].Members[1];
			
			CodeVariableDeclarationStatement s0 = (CodeVariableDeclarationStatement)m.Statements[0];
			Assert.AreEqual("panel1", s0.Name);
			Assert.AreEqual("System.Windows.Forms.Panel", s0.Type.BaseType);
			
			CodeAssignStatement cas = (CodeAssignStatement)m.Statements[1];
			Assert.AreEqual("closeButton", ((CodeFieldReferenceExpression)cas.Left).FieldName);
			
			cas = (CodeAssignStatement)m.Statements[2];
			Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)cas.Left).VariableName);
			
			CodeExpressionStatement ces = (CodeExpressionStatement)m.Statements[3];
			CodeMethodInvokeExpression mie = (CodeMethodInvokeExpression)ces.Expression;
			Assert.AreEqual("SuspendLayout", mie.Method.MethodName);
			Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)mie.Method.TargetObject).VariableName);
			
			ces = (CodeExpressionStatement)m.Statements[4];
			mie = (CodeMethodInvokeExpression)ces.Expression;
			Assert.AreEqual("Add", mie.Method.MethodName);
			CodePropertyReferenceExpression pre = (CodePropertyReferenceExpression)mie.Method.TargetObject;
			Assert.AreEqual("Controls", pre.PropertyName);
			Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)pre.TargetObject).VariableName);
			
			cas = (CodeAssignStatement)m.Statements[5];
			pre = (CodePropertyReferenceExpression)cas.Left;
			Assert.AreEqual("BackColor", pre.PropertyName);
			Assert.AreEqual("closeButton", ((CodeFieldReferenceExpression)pre.TargetObject).FieldName);
			mie = (CodeMethodInvokeExpression)cas.Right;
			Assert.AreEqual("FromArgb", mie.Method.MethodName);
			Assert.IsTrue(mie.Method.TargetObject is CodeTypeReferenceExpression);
			Assert.AreEqual("System.Drawing.Color", (mie.Method.TargetObject as CodeTypeReferenceExpression).Type.BaseType);
			
			cas = (CodeAssignStatement)m.Statements[6];
			pre = (CodePropertyReferenceExpression)cas.Left;
			Assert.AreEqual("BackColor", pre.PropertyName);
			Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)pre.TargetObject).VariableName);
			pre = (CodePropertyReferenceExpression)cas.Right;
			Assert.AreEqual("Info", pre.PropertyName);
			Assert.IsTrue(pre.TargetObject is CodeTypeReferenceExpression);
			Assert.AreEqual("System.Drawing.SystemColors", (pre.TargetObject as CodeTypeReferenceExpression).Type.BaseType);
		}
 public ICompilationUnit ConvertCompilationUnit(CompilationUnit compilationUnit)
 {
     var converter = new NRefactoryASTConvertVisitor(myProjectContent);
     compilationUnit.AcceptVisitor(converter, null);            
     return converter.Cu;
 }
        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);
        }
Пример #21
0
 public GetAllINodes(CompilationUnit compilationUnit) : this()
 {
 	compilationUnit.AcceptVisitor(this,null);
 }
        // DC

        //DC

        /*public void loadCode(string code)
         * {
         *  code = (code.fileExists()) ? code.fileContents() : code;
         *  var parser = code.csharpAst();
         *  loadCompilationUnit(parser.CompilationUnit);
         * }*/
        //DC
        public void loadCompilationUnit(NRefactoryAST.CompilationUnit compilationUnit)
        {
            cu = new DefaultCompilationUnit(defaultProjectContent);
            compilationUnit.AcceptVisitor(this, null);
        }
Пример #23
0
		protected override void ConvertAst(CompilationUnit compilationUnit, List<ISpecial> specials)
		{
			PreprocessingDirective.VBToCSharp(specials);
			compilationUnit.AcceptVisitor(new VBNetToCSharpConvertVisitor(), null);
		}
		public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
		{
			base.VisitCompilationUnit(compilationUnit, data);
			compilationUnit.AcceptVisitor(new ToCSharpConvertVisitor(), data);
			return null;
		}
Пример #25
0
        private string LinqQueryToImplicitClass()
        {
            var parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(source));
            var block = parser.ParseBlock();

            var visitor = new TransformVisitor();
            block.AcceptVisitor(visitor, null);

            VariableDeclaration variable = GetVariableDeclaration(block);

            Name = variable.Name;

            var type = new TypeDeclaration(Modifiers.Public, new List<AttributeSection>())
            {
                BaseTypes =
                    {
                        new TypeReference("AbstractViewGenerator")
                    },
                Name = Name,
                Type = ClassType.Class
            };

            var ctor = new ConstructorDeclaration(Name,
                                                  Modifiers.Public,
                                                  new List<ParameterDeclarationExpression>(), null);
            type.Children.Add(ctor);
            ctor.Body = new BlockStatement();
            ctor.Body.AddChild(new ExpressionStatement(
                                   new AssignmentExpression(
                                       new MemberReferenceExpression(new ThisReferenceExpression(), "ViewText"),
                                       AssignmentOperatorType.Assign,
                                       new PrimitiveExpression(source, source))));
            ctor.Body.AddChild(new ExpressionStatement(
                                   new AssignmentExpression(
                                       new MemberReferenceExpression(new ThisReferenceExpression(), "ViewDefinition"),
                                       AssignmentOperatorType.Assign,
                                       new LambdaExpression
                                       {
                                           Parameters =
                                               {
                                                   new ParameterDeclarationExpression(new TypeReference("System.Collections.Generic.IEnumerable<"+rootQueryType+">"), rootQueryName)
                                               },
                                           ExpressionBody = variable.Initializer
                                       })));

            var unit = new CompilationUnit();
            unit.AddChild(new Using(typeof(AbstractViewGenerator).Namespace));
            unit.AddChild(new Using(typeof(System.Linq.Enumerable).Namespace));
            unit.AddChild(type);

            var output = new CSharpOutputVisitor();
            unit.AcceptVisitor(output, null);

            return output.Text;
        }
Пример #26
0
 private ICompilationUnit ConvertCompilationUnit(CompilationUnit cu)
 {
     NRefactoryASTConvertVisitor converter;
     converter = new NRefactoryASTConvertVisitor(myProjectContent);
     cu.AcceptVisitor(converter, null);
     return converter.Cu;
 }
Пример #27
0
        public void mapAstDetails(CompilationUnit unit)
        {
            try
            {
                CompilationUnit = unit;

                AstDetails = new AstDetails();
                var specials = Parser.Lexer.SpecialTracker.RetrieveSpecials();
                specials.AddRange(ExtraSpecials);
                AstDetails.mapSpecials(specials);
                AstDetails.rewriteCode_CSharp(CompilationUnit, specials);
                AstDetails.rewriteCode_VBNet(CompilationUnit, specials);

                CompilationUnit.AcceptVisitor(AstDetails, null);
            }
            catch(Exception ex)
            {
                PublicDI.log.error("in mapAstDetails: {0}", ex.Message);
            }
        }