public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
		{
			_treeService.PushArea("Components");
			object r = base.VisitCompilationUnit(compilationUnit, data);
			_treeService.PopNode();
			return base.VisitCompilationUnit(compilationUnit, data);
		}
		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;
		}
 internal void SetupParsedCompilationUnit(ICSharpCode.NRefactory.Ast.CompilationUnit unit)
 {
     lookupVariableLine    = 0;          // all compilation unit lines are 1 based
     memberCompilationUnit = unit;
     lookupTableVisitor.VisitCompilationUnit(unit, null);
     setupLookupTableVisitor = true;
 }
Exemple #4
0
/*

*/

	void VBNET() {

#line  231 "VBNET.ATG" 
		lexer.NextToken(); // get the first token
		compilationUnit = new CompilationUnit();
		
		while (la.kind == 1) {
			lexer.NextToken();
		}
		while (la.kind == 136) {
			OptionStmt();
		}
		while (la.kind == 108) {
			ImportsStmt();
		}
		while (
#line  237 "VBNET.ATG" 
IsGlobalAttrTarget()) {
			GlobalAttributeSection();
		}
		while (StartOf(1)) {
			NamespaceMemberDecl();
		}
		Expect(0);
	}
		public object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
		{
			module = new B.Module();
			module.LexicalInfo = new B.LexicalInfo(fileName, 1, 1);
			compilationUnit.AcceptChildren(this, data);
			if (entryPointMethod != null) {
				bool allMembersAreStatic = true;
				foreach (B.TypeMember member in entryPointMethod.DeclaringType.Members) {
					allMembersAreStatic &= member.IsStatic;
				}
				if (allMembersAreStatic) {
					entryPointMethod.DeclaringType.Attributes.Add(MakeAttribute(("module")));
				} else {
					lastLexicalInfo = entryPointMethod.LexicalInfo;
					B.Expression expr = MakeReferenceExpression(entryPointMethod.DeclaringType.Name + ".Main");
					B.MethodInvocationExpression mie = new B.MethodInvocationExpression(lastLexicalInfo, expr);
					if (entryPointMethod.Parameters.Count > 0) {
						mie.Arguments.Add(MakeReferenceExpression("argv"));
					}
					B.SimpleTypeReference ret = entryPointMethod.ReturnType as B.SimpleTypeReference;
					if (ret.Name == "void" || ret.Name == "System.Void")
						module.Globals.Add(new B.ExpressionStatement(mie));
					else
						module.Globals.Add(new B.ReturnStatement(lastLexicalInfo, mie, null));
				}
			}
			B.Module tmp = module;
			module = null;
			return tmp;
		}
		void CheckAliases(CompilationUnit u)
		{
			Assert.AreEqual(3, u.Children.Count);
			
			Assert.IsTrue(u.Children[0] is UsingDeclaration);
			UsingDeclaration ud = (UsingDeclaration)u.Children[0];
			Assert.AreEqual(1, ud.Usings.Count);
			Assert.IsTrue(((Using)ud.Usings[0]).IsAlias);
			Assert.AreEqual("TESTME", ud.Usings[0].Name);
			Assert.AreEqual("System", ud.Usings[0].Alias.Type);
			
			Assert.IsTrue(u.Children[1] is UsingDeclaration);
			ud = (UsingDeclaration)u.Children[1];
			Assert.AreEqual(1, ud.Usings.Count);
			Assert.IsTrue(((Using)ud.Usings[0]).IsAlias);
			Assert.AreEqual("myAlias", ud.Usings[0].Name);
			Assert.AreEqual("My.Name.Space", ud.Usings[0].Alias.Type);
			
			Assert.IsTrue(u.Children[2] is UsingDeclaration);
			ud = (UsingDeclaration)u.Children[2];
			Assert.AreEqual(1, ud.Usings.Count);
			Assert.IsTrue(((Using)ud.Usings[0]).IsAlias);
			Assert.AreEqual("StringCollection", ud.Usings[0].Name);
			Assert.AreEqual("System.Collections.Generic.List", ud.Usings[0].Alias.Type);
			Assert.AreEqual("System.String", ud.Usings[0].Alias.GenericTypes[0].Type);
		}
		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;
									}
								}
							}
						}
					}
				}
			}
		}
		public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
		{
			base.VisitCompilationUnit(compilationUnit, data);
			ToVBNetConvertVisitor v = new ToVBNetConvertVisitor();
			compilationUnit.AcceptVisitor(v, data);
			return null;
		}
		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;
		}
		INode Parse(SupportedLanguage sourceLanguage, string sourceCode, out string error)
		{
			project = new DefaultProjectContent();
			project.ReferencedContents.AddRange(ReferencedContents);
			if (sourceLanguage == SupportedLanguage.VBNet) {
				project.Language = LanguageProperties.VBNet;
				project.DefaultImports = new DefaultUsing(project);
				project.DefaultImports.Usings.AddRange(DefaultImportsToAdd);
			} else {
				project.Language = LanguageProperties.CSharp;
			}
			SnippetParser parser = new SnippetParser(sourceLanguage);
			INode result = parser.Parse(sourceCode);
			error = parser.Errors.ErrorOutput;
			specials = parser.Specials;
			if (parser.Errors.Count != 0)
				return null;
			
			wasExpression = parser.SnippetType == SnippetType.Expression;
			if (wasExpression) {
				// Special case 'Expression': expressions may be replaced with other statements in the AST by the ConvertVisitor,
				// but we need to return a 'stable' node so that the correct transformed AST is returned.
				// Thus, we wrap any expressions into a statement block.
				result = MakeBlockFromExpression((Expression)result);
			}
			
			// now create a dummy compilation unit around the snippet result
			switch (parser.SnippetType) {
				case SnippetType.CompilationUnit:
					compilationUnit = (CompilationUnit)result;
					break;
				case SnippetType.Expression:
				case SnippetType.Statements:
					compilationUnit = MakeCompilationUnitFromTypeMembers(
						MakeMethodFromBlock(
							(BlockStatement)result
						));
					break;
				case SnippetType.TypeMembers:
					compilationUnit = MakeCompilationUnitFromTypeMembers(result.Children);
					break;
				default:
					throw new NotSupportedException("Unknown snippet type: " + parser.SnippetType);
			}
			
			// convert NRefactory CU in DOM CU
			NRefactoryASTConvertVisitor visitor = new NRefactoryASTConvertVisitor(project);
			visitor.VisitCompilationUnit(compilationUnit, null);
			visitor.Cu.FileName = sourceLanguage == SupportedLanguage.CSharp ? "a.cs" : "a.vb";
			
			// and register the compilation unit in the DOM
			foreach (IClass c in visitor.Cu.Classes) {
				project.AddClassToNamespaceList(c);
			}
			parseInfo = new ParseInformation();
			parseInfo.SetCompilationUnit(visitor.Cu);
			
			return result;
		}
        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);
        }
		public API_ASMX_Proxy SetUp()
		{
			PropName 			  = "_web_Service";
			Proxy_CompilationUnit = new CompilationUnit();			
			Proxy_CompilationUnit.add_Using("System");
			Proxy_CompilationUnit.add_Using("System.Web.Services"); 			
			return this;
		}	
Exemple #13
0
        public Ast_CSharp(CompilationUnit unit, List<ISpecial> extraSpecials)
        {
            createAst("");
            ExtraSpecials = extraSpecials;
            mapAstDetails(unit);

            //mapAstDetails(Parser.CompilationUnit);
        }
Exemple #14
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;
 }
		public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
		{
			base.VisitCompilationUnit(compilationUnit, data);
			for (int i = 0; i < nodesToMoveToCompilationUnit.Count; i++) {
				compilationUnit.Children.Insert(i, nodesToMoveToCompilationUnit[i]);
				nodesToMoveToCompilationUnit[i].Parent = compilationUnit;
			}
			return null;
		}
        public override List <Change> PerformChanges(RefactoringOptions options, object properties)
        {
            List <Change> result = new List <Change> ();

            ICSharpCode.NRefactory.Ast.CompilationUnit unit = options.GetASTProvider().ParseFile(options.Document.Editor.Text);
            FindTypeReferencesVisitor visitor = new FindTypeReferencesVisitor(options.GetTextEditorData(), options.GetResolver());

            visitor.VisitCompilationUnit(unit, null);

            ProjectDom dom = options.Dom;

            ICompilationUnit compilationUnit = options.ParseDocument().CompilationUnit;
            HashSet <string> usedUsings      = new HashSet <string> ();

            foreach (TypeReference r in visitor.PossibleTypeReferences)
            {
                if (r.IsKeyword)
                {
                    continue;
                }
                IType type = dom.SearchType(compilationUnit, options.ResolveResult.CallingType, new DomLocation(options.Document.Editor.Caret.Line, options.Document.Editor.Caret.Column), r.ConvertToReturnType());
                if (type != null)
                {
                    usedUsings.Add(type.Namespace);
                }
            }

            Mono.TextEditor.TextEditorData textEditorData = options.GetTextEditorData();
            HashSet <string> currentUsings = new HashSet <string> ();

            foreach (IUsing u in compilationUnit.Usings)
            {
                if (u.IsFromNamespace)
                {
                    continue;
                }
                if (!u.Aliases.Any() && u.Namespaces.All(name => currentUsings.Contains(name) || !usedUsings.Contains(name)))
                {
                    TextReplaceChange change = new TextReplaceChange();
                    change.FileName     = options.Document.FileName;
                    change.Offset       = textEditorData.Document.LocationToOffset(u.Region.Start.Line, u.Region.Start.Column);
                    change.RemovedChars = textEditorData.Document.LocationToOffset(u.Region.End.Line, u.Region.End.Column) - change.Offset;
                    Mono.TextEditor.LineSegment line = textEditorData.Document.GetLineByOffset(change.Offset);
                    if (line != null && line.EditableLength == change.RemovedChars)
                    {
                        change.RemovedChars += line.DelimiterLength;
                    }
                    result.Add(change);
                }
                foreach (string nspace in u.Namespaces)
                {
                    currentUsings.Add(nspace);
                }
            }

            return(result);
        }
        public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
        {
            Contract.Requires(compilationUnit != null);

            // Visit children (E.g. TypeDcelarion objects)
            compilationUnit.AcceptChildren(this, data);

            return null;
        }
 public override object VisitCompilationUnit(AST.CompilationUnit compilationUnit, object data)
 {
     if (compilationUnit == null)
     {
         return(null);
     }
     compilationUnit.AcceptChildren(this, data);
     return(cu);
 }
Exemple #19
0
 public static Expression GetStatementNodeOf(CompilationUnit compilationUnit, int index)
 {
     NamespaceDeclaration ns = (NamespaceDeclaration) compilationUnit.Children[0];
     TypeDeclaration ty = (TypeDeclaration) ns.Children[0];
     MethodDeclaration md = (MethodDeclaration) ty.Children[0];
     ExpressionStatement st = (ExpressionStatement) md.Body.Children[index];
     Expression exp = st.Expression;
     return exp;
 }
		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 override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
        {
            Contract.Requires(compilationUnit != null);

            DictClass = new Dictionary<string, ClassStructure>();
            // Visit children (E.g. TypeDcelarion objects)
            compilationUnit.AcceptChildren(this, data);

            return 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;            
 }
		INode Parse(SupportedLanguage sourceLanguage, string sourceCode, out string error)
		{
			project = new DefaultProjectContent();
			project.ReferencedContents.AddRange(ReferencedContents);
			if (sourceLanguage == SupportedLanguage.VBNet) {
				project.DefaultImports = new DefaultUsing(project);
				project.DefaultImports.Usings.AddRange(DefaultImportsToAdd);
			}
			SnippetParser parser = new SnippetParser(sourceLanguage);
			INode result = parser.Parse(sourceCode);
			error = parser.Errors.ErrorOutput;
			specials = parser.Specials;
			if (parser.Errors.Count != 0)
				return null;
			
			// now create a dummy compilation unit around the snippet result
			switch (parser.SnippetType) {
				case SnippetType.CompilationUnit:
					compilationUnit = (CompilationUnit)result;
					break;
				case SnippetType.Expression:
					compilationUnit = MakeCompilationUnitFromTypeMembers(
						MakeMethodFromBlock(
							MakeBlockFromExpression(
								(Expression)result
							)));
					break;
				case SnippetType.Statements:
					compilationUnit = MakeCompilationUnitFromTypeMembers(
						MakeMethodFromBlock(
							(BlockStatement)result
						));
					break;
				case SnippetType.TypeMembers:
					compilationUnit = MakeCompilationUnitFromTypeMembers(result.Children);
					break;
				default:
					throw new NotSupportedException("Unknown snippet type: " + parser.SnippetType);
			}
			
			// convert NRefactory CU in DOM CU
			NRefactoryASTConvertVisitor visitor = new NRefactoryASTConvertVisitor(project);
			visitor.VisitCompilationUnit(compilationUnit, null);
			visitor.Cu.FileName = sourceLanguage == SupportedLanguage.CSharp ? "a.cs" : "a.vb";
			
			// and register the compilation unit in the DOM
			foreach (IClass c in visitor.Cu.Classes) {
				project.AddClassToNamespaceList(c);
			}
			parseInfo = new ParseInformation();
			parseInfo.SetCompilationUnit(visitor.Cu);
			
			return result;
		}
Exemple #25
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);
        }
Exemple #26
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");
        }
    }
    public void VisitCompileUnit_Always_PushesComponentsArea()
    {
      CompilationUnit cu = new CompilationUnit();

      using (_mocks.Unordered())
      {
        _treeService.PushArea("Components");
        _treeService.PopNode();
      }

      _mocks.ReplayAll();
      _visitor.VisitCompilationUnit(cu, null);
      _mocks.VerifyAll();
    }
Exemple #28
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;
        }
		void CheckTwoSimpleUsings(CompilationUnit u)
		{
			Assert.AreEqual(2, u.Children.Count);
			Assert.IsTrue(u.Children[0] is UsingDeclaration);
			UsingDeclaration ud = (UsingDeclaration)u.Children[0];
			Assert.AreEqual(1, ud.Usings.Count);
			Assert.IsTrue(!ud.Usings[0].IsAlias);
			Assert.AreEqual("System", ud.Usings[0].Name);
			
			
			Assert.IsTrue(u.Children[1] is UsingDeclaration);
			ud = (UsingDeclaration)u.Children[1];
			Assert.AreEqual(1, ud.Usings.Count);
			Assert.IsTrue(!ud.Usings[0].IsAlias);
			Assert.AreEqual("My.Name.Space", ud.Usings[0].Name);
		}
		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);
		}
        internal void SetupResolver(DomLocation resolvePosition)
        {
            this.resolvePosition = resolvePosition;
            this.resultTable.Clear();
            callingType = GetTypeAtCursor(unit, fileName, resolvePosition);

            if (callingType != null)
            {
                callingMember = GetMemberAt(callingType, fileName, resolvePosition);
                callingType   = dom.ResolveType(callingType);
                if (callingMember == null)
                {
                    DomLocation posAbove = resolvePosition;
                    posAbove.Line--;
                    callingMember = GetMemberAt(callingType, fileName, posAbove);
                }
            }

            if (memberCompilationUnit != null)
            {
                return;
            }
            if (callingMember != null && !setupLookupTableVisitor)
            {
                string wrapper = CreateWrapperClassForMember(callingMember, fileName, editor);
                using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(lang, new StringReader(wrapper))) {
                    parser.Parse();
                    memberCompilationUnit = parser.CompilationUnit;
                    lookupTableVisitor.VisitCompilationUnit(parser.CompilationUnit, null);
                    lookupVariableLine      = CallingMember.Location.Line - 2;
                    setupLookupTableVisitor = true;
                }
            }
            else if (editor != null)
            {
                string wrapper = editor.Text;
                using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(lang, new StringReader(wrapper))) {
                    parser.Parse();
                    memberCompilationUnit = parser.CompilationUnit;
                    lookupTableVisitor.VisitCompilationUnit(parser.CompilationUnit, null);
                    lookupVariableLine      = 0;
                    setupLookupTableVisitor = true;
                }
            }
        }
		public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
		{
			usings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
			addedUsings = new List<UsingDeclaration>();
			base.VisitCompilationUnit(compilationUnit, data);
			int i;
			for (i = 0; i < compilationUnit.Children.Count; i++) {
				if (!(compilationUnit.Children[i] is UsingDeclaration))
					break;
			}
			foreach (UsingDeclaration decl in addedUsings) {
				decl.Parent = compilationUnit;
				compilationUnit.Children.Insert(i++, decl);
			}
			usings = null;
			addedUsings = null;
			return null;
		}
    public void Parse()
    {
      CompilationUnit unit = new CompilationUnit();

      using (_mocks.Unordered())
      {
        Expect.Call(_parserFactory.CreateCSharpParser(null)).Constraints(Is.NotNull()).Return(_parser);
        _parser.ParseMethodBodies = true;
        _parser.Parse();
        _typeResolver.Clear();
        Expect.Call(_parser.CompilationUnit).Return(unit);
        Expect.Call(_visitor.VisitCompilationUnit(unit, null)).Return(null);
        _sources.Add(_path, _parser);
      }

      _mocks.ReplayAll();
      _service.Parse(_visitor, _path);
      _mocks.VerifyAll();
    }
	    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);
			}
	    }
 public override object VisitCompilationUnit(AST.CompilationUnit compilationUnit, object data)
 {
     if (compilationUnit == null)
     {
         return(null);
     }
     currentNamespace = new DefaultUsingScope();
     if (!string.IsNullOrEmpty(VBRootNamespace))
     {
         foreach (string name in VBRootNamespace.Split('.'))
         {
             currentNamespace = new DefaultUsingScope();
             currentNamespace.NamespaceName = PrependCurrentNamespace(name);
             currentNamespace.Parent        = currentNamespace;
             currentNamespace.Parent.ChildScopes.Add(currentNamespace);
         }
     }
     cu.UsingScope = currentNamespace;
     compilationUnit.AcceptChildren(this, data);
     return(cu);
 }
        public void RunVisitor(ICSharpCode.NRefactory.Ast.CompilationUnit compilationUnit)
        {
            if (searchedMembers.Count == 0)
            {
                return;
            }
            // search if the member name exists in the file (otherwise it doesn't make sense to search it)
            FindReplace   findReplace   = new FindReplace();
            FilterOptions filterOptions = new FilterOptions {
                CaseSensitive  = true,
                WholeWordsOnly = true
            };
            IEnumerable <SearchResult> result = findReplace.Search(new FileProvider(null), text.Text, SearchedMemberName, null, filterOptions);

            if (result == null || !result.Any())
            {
                return;
            }
            resolver.SetupParsedCompilationUnit(compilationUnit);
            VisitCompilationUnit(compilationUnit, null);
        }
Exemple #37
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));
 }
Exemple #38
0
//#line  13 "VBNET.ATG" 


/*

*/

	void VBNET() {

//#line  263 "VBNET.ATG" 
		lexer.NextToken(); // get the first token
		compilationUnit = new CompilationUnit();
		BlockStart(compilationUnit);
		
		while (la.kind == 1 || la.kind == 21) {
			EndOfStmt();
		}
		while (la.kind == 173) {
			OptionStmt();
			while (la.kind == 1 || la.kind == 21) {
				EndOfStmt();
			}
		}
		while (la.kind == 137) {
			ImportsStmt();
			while (la.kind == 1 || la.kind == 21) {
				EndOfStmt();
			}
		}
		while (
//#line  271 "VBNET.ATG" 
IsGlobalAttrTarget()) {
			GlobalAttributeSection();
			while (la.kind == 1 || la.kind == 21) {
				EndOfStmt();
			}
		}
		while (StartOf(1)) {
			NamespaceMemberDecl();
			while (la.kind == 1 || la.kind == 21) {
				EndOfStmt();
			}
		}
		Expect(0);
	}
 //DC
 public void mapCompilationUnit(NRefactoryAST.CompilationUnit compilationUnit, ICompilationUnit iCompilationUnit)
 {
     CompilationUnitToICompilationUnit.Add(compilationUnit, iCompilationUnit);
 }
        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);
        }
        // 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);
        }
        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);
        }
Exemple #43
0
 public override object VisitCompilationUnit(ICSharpCode.NRefactory.Ast.CompilationUnit compilationUnit, object data)
 {
     variables.Clear();
     return(base.VisitCompilationUnit(compilationUnit, data));
 }