Example #1
0
        public void HasImportReturnsTrueForImportThatDoesExistInCompilationUnitWithSingleUsingWithMultipleNamespaces()
        {
            string           code      = "import abc, ghi";
            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);

            PythonResolverContext resolverContext = new PythonResolverContext(parseInfo);

            Assert.IsTrue(resolverContext.HasImport("ghi"));
        }
Example #2
0
 public CSharpExpressionFinder(ParseInformation parseInformation)
 {
     this.parseInformation = parseInformation;
     if (parseInformation != null && parseInformation.MostRecentCompilationUnit != null) {
         projectContent = parseInformation.MostRecentCompilationUnit.ProjectContent;
     } else {
         projectContent = DefaultProjectContent.DummyProjectContent;
     }
 }
        public void HasDottedImportNameReturnsFalseForMyNamespaceWithMyNamespaceTestImportedWithoutDtso()
        {
            string           code      = "import MyNamespaceTest";
            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);

            PythonResolverContext resolverContext = new PythonResolverContext(parseInfo);

            Assert.IsFalse(resolverContext.HasDottedImportNameThatStartsWith("MyNamespace"));
        }
        public void HasDottedImportNameReturnsTrueForSystemWithSystemWindowsFormsImported()
        {
            string           code      = "import System.Windows.Forms";
            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);

            PythonResolverContext resolverContext = new PythonResolverContext(parseInfo);

            Assert.IsTrue(resolverContext.HasDottedImportNameThatStartsWith("System"));
        }
Example #5
0
        public void HasImportReturnsTrueForImportedAsName()
        {
            string           code      = "import sys as something";
            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);

            PythonResolverContext resolverContext = new PythonResolverContext(parseInfo);

            Assert.IsTrue(resolverContext.HasImport("something"));
        }
Example #6
0
        public void HasImportReturnsFalseForFromImport()
        {
            string           code      = "from import sys";
            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);

            PythonResolverContext resolverContext = new PythonResolverContext(parseInfo);

            Assert.IsFalse(resolverContext.HasImport("sys"));
        }
Example #7
0
        public void HasImportReturnsTrueForImportThatDoesExistInCompilationUnit()
        {
            string           code      = "import abc";
            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);

            PythonResolverContext resolverContext = new PythonResolverContext(parseInfo);

            Assert.IsTrue(resolverContext.HasImport("abc"));
        }
Example #8
0
        void TestProgram(SupportedLanguage sourceLanguage, string sourceCode, string expectedOutput)
        {
            DefaultProjectContent pc = new DefaultProjectContent();

            pc.ReferencedContents.Add(projectContentRegistry.Mscorlib);
            pc.ReferencedContents.Add(projectContentRegistry.GetProjectContentForReference("System.Windows.Forms", typeof(System.Windows.Forms.Form).Module.FullyQualifiedName));
            if (sourceLanguage == SupportedLanguage.VBNet)
            {
                pc.ReferencedContents.Add(projectContentRegistry.GetProjectContentForReference("Microsoft.VisualBasic", typeof(Microsoft.VisualBasic.Constants).Module.FullyQualifiedName));
                pc.DefaultImports = new DefaultUsing(pc);
                pc.DefaultImports.Usings.Add("System");
                pc.DefaultImports.Usings.Add("Microsoft.VisualBasic");
            }
            pc.Language = sourceLanguage == SupportedLanguage.CSharp ? LanguageProperties.CSharp : LanguageProperties.VBNet;
            HostCallback.GetCurrentProjectContent = delegate {
                return(pc);
            };

            ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(sourceLanguage, new StringReader(sourceCode));
            parser.Parse();
            Assert.AreEqual("", parser.Errors.ErrorOutput);

            NRefactoryASTConvertVisitor visitor = new NRefactoryASTConvertVisitor(pc, sourceLanguage);

            visitor.VisitCompilationUnit(parser.CompilationUnit, null);
            visitor.Cu.FileName = sourceLanguage == SupportedLanguage.CSharp ? "a.cs" : "a.vb";
            foreach (IClass c in visitor.Cu.Classes)
            {
                pc.AddClassToNamespaceList(c);
            }

            ParseInformation parseInfo = new ParseInformation(visitor.Cu);

            if (sourceLanguage == SupportedLanguage.CSharp)
            {
                CSharpToVBNetConvertVisitor convertVisitor = new CSharpToVBNetConvertVisitor(pc, parseInfo);
                convertVisitor.RootNamespaceToRemove = "RootNamespace";
                parser.CompilationUnit.AcceptVisitor(convertVisitor, null);
            }
            else
            {
                VBNetToCSharpConvertVisitor convertVisitor = new VBNetToCSharpConvertVisitor(pc, parseInfo);
                parser.CompilationUnit.AcceptVisitor(convertVisitor, null);
            }

            IOutputAstVisitor outputVisitor = sourceLanguage == SupportedLanguage.CSharp ? (IOutputAstVisitor) new VBNetOutputVisitor() : new CSharpOutputVisitor();

            outputVisitor.Options.IndentationChar = ' ';
            outputVisitor.Options.IndentSize      = 2;
            using (SpecialNodesInserter.Install(parser.Lexer.SpecialTracker.RetrieveSpecials(),
                                                outputVisitor)) {
                outputVisitor.VisitCompilationUnit(parser.CompilationUnit, null);
            }
            Assert.AreEqual("", outputVisitor.Errors.ErrorOutput);
            Assert.AreEqual(expectedOutput.Replace("\r", ""), outputVisitor.Text.Trim().Replace("\r", ""));
        }
Example #9
0
        public void GetModulesThatImportEverythingReturnsEmptyCollectionIfNotImportAll()
        {
            string           code      = "from math import tan";
            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);

            PythonResolverContext resolverContext = new PythonResolverContext(parseInfo);

            string[] expectedModules = new string[0];
            Assert.AreEqual(expectedModules, resolverContext.GetModulesThatImportEverything());
        }
Example #10
0
        public ResolveResult Resolve(ParseInformation parseInfo, TextLocation location, ICompilation compilation, CancellationToken cancellationToken)
        {
            var decompiledParseInfo = parseInfo as ILSpyFullParseInformation;

            if (decompiledParseInfo == null)
            {
                throw new ArgumentException("ParseInfo does not have SyntaxTree");
            }
            return(ResolveAtLocation.Resolve(compilation, null, decompiledParseInfo.SyntaxTree, location, cancellationToken));
        }
        public void GetCompatibleMethods_OneMethodWithNoParameters_NoMethodsReturnedInCompatibleMethods()
        {
            CreateDesignerGenerator();
            ParseInformation parseInfo = generator.CreateParseInfoWithOneMethod("button1_click");

            generator.ParseInfoToReturnFromParseFile = parseInfo;
            ICollection methods = CallGetCompatibleMethods();

            Assert.AreEqual(0, methods.Count);
        }
Example #12
0
        /// <summary>
        /// Returns CodeGenerator for C# or VB depending on the current file where snippet is being inserted.
        /// </summary>
        CodeGenerator GetCodeGeneratorForCurrentFile()
        {
            ParseInformation parseInfo = ParserService.GetParseInformation(this.Editor.FileName);

            if (parseInfo != null)
            {
                return(parseInfo.CompilationUnit.Language.CodeGenerator);
            }
            return(null);
        }
Example #13
0
        public void Init()
        {
            DefaultProjectContent  projectContent = new DefaultProjectContent();
            DefaultCompilationUnit unit           = new DefaultCompilationUnit(projectContent);

            existingParseInfo = new ParseInformation(unit);

            parserService = new MockParserService();
            parserService.SetExistingParseInformation(@"d:\projects\test.xml", existingParseInfo);
        }
Example #14
0
        public void GetModulesThatImportEverythingReturnsSysForFromSysImportAllStatement()
        {
            string           code      = "from sys import *";
            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);

            PythonResolverContext resolverContext = new PythonResolverContext(parseInfo);

            string[] expectedModules = new string[] { "sys" };
            Assert.AreEqual(expectedModules, resolverContext.GetModulesThatImportEverything());
        }
Example #15
0
        public void Init()
        {
            ParseInformation parseInfo = new ParseInformation();

            projectContent = new MockProjectContent();

            PythonImportCompletion completion = new PythonImportCompletion(projectContent);

            completionItems = completion.GetCompletionItems(String.Empty);
        }
        public void CreateParseInfoReturnsParseInfoWithSingleClass()
        {
            string code =
                "class foo:\r\n" +
                "    pass";

            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);

            Assert.AreEqual("foo", parseInfo.CompilationUnit.Classes[0].Name);
        }
Example #17
0
        IProjectContent GetProjectContentForFile()
        {
            ParseInformation parseInfo = ParserService.GetParseInformation(this.DesignerCodeFile.FileName);

            if (parseInfo != null)
            {
                return(parseInfo.CompilationUnit.ProjectContent);
            }
            return(DefaultProjectContent.DummyProjectContent);
        }
 void ParseInformationUpdatedInvoked(ParseInformation parseInfo)
 {
     try {
         textEditor.Document.FoldingManager.UpdateFoldings(file.FileName, parseInfo);
         textEditor.ActiveTextAreaControl.TextArea.Refresh(textEditor.ActiveTextAreaControl.TextArea.FoldMargin);
         textEditor.ActiveTextAreaControl.TextArea.Refresh(textEditor.ActiveTextAreaControl.TextArea.IconBarMargin);
     } catch (Exception ex) {
         MessageService.ShowError(ex);
     }
 }
        public PythonResolverTestsHelper(string code)
        {
            ProjectContent = new ScriptingUtils.MockProjectContent();
            PythonParser parser   = new PythonParser();
            string       fileName = @"test.py";

            CompilationUnit = parser.Parse(ProjectContent, fileName, code) as DefaultCompilationUnit;

            ParseInfo = new ParseInformation(CompilationUnit);
            Resolver  = new PythonResolver();
        }
 public void SetUp()
 {
     displayBinding = new DerivedRubyFormsDesignerDisplayBinding();
     viewContent    = new MockTextEditorViewContent();
     viewContent.PrimaryFileName          = new FileName("test.rb");
     viewContent.TextEditor.Document.Text = "text content";
     parseInfo = new ParseInformation(new DefaultCompilationUnit(new DefaultProjectContent()));
     displayBinding.ParseServiceParseInfoToReturn = parseInfo;
     displayBinding.IsParseInfoDesignable         = true;
     canAttachToDesignableClass = displayBinding.CanAttachTo(viewContent);
 }
        InsertCtorDialog CreateDialog(InsertionContext context)
        {
            ITextEditor textEditor = context.TextArea.GetService(typeof(ITextEditor)) as ITextEditor;

            if (textEditor == null)
            {
                return(null);
            }

            IEditorUIService uiService = textEditor.GetService(typeof(IEditorUIService)) as IEditorUIService;

            if (uiService == null)
            {
                return(null);
            }

            ParseInformation parseInfo = ParserService.GetParseInformation(textEditor.FileName);

            if (parseInfo == null)
            {
                return(null);
            }

            CodeGenerator generator = parseInfo.CompilationUnit.Language.CodeGenerator;

            // cannot use insertion position at this point, because it might not be
            // valid, because we are still generating the elements.
            // DOM is not updated
            ICSharpCode.AvalonEdit.Document.TextLocation loc = context.Document.GetLocation(context.StartPosition);

            IClass current = parseInfo.CompilationUnit.GetInnermostClass(loc.Line, loc.Column);

            if (current == null)
            {
                return(null);
            }

            List <PropertyOrFieldWrapper> parameters = CreateCtorParams(current).ToList();

            if (!parameters.Any())
            {
                return(null);
            }

            ITextAnchor anchor = textEditor.Document.CreateAnchor(context.InsertionPosition);

            anchor.MovementType = AnchorMovementType.BeforeInsertion;

            InsertCtorDialog dialog = new InsertCtorDialog(context, textEditor, anchor, current, parameters);

            dialog.Element = uiService.CreateInlineUIElement(anchor, dialog);

            return(dialog);
        }
 public void SetUp()
 {
     displayBinding = new DerivedRubyFormsDesignerDisplayBinding();
     viewContent    = new MockTextEditorViewContent();
     viewContent.PrimaryFileName        = "test.rb";
     viewContent.TextEditorControl.Text = "text content";
     parseInfo = new ParseInformation();
     displayBinding.ParseServiceParseInfoToReturn = parseInfo;
     displayBinding.IsParseInfoDesignable         = true;
     canAttachToDesignableClass = displayBinding.CanAttachTo(viewContent);
 }
Example #23
0
            public override ResolveResult Resolve(ITextEditor editor, ExpressionResult expressionResult)
            {
                // bypass ParserService.Resolve and set resolver.LimitMethodExtractionUntilCaretLine
                ParseInformation parseInfo = ParserService.GetParseInformation(editor.Document.Text, ProjectContent);
                var resolver = new NRefactoryResolver(LanguageProperties.CSharp)
                {
                    LimitMethodExtractionUntilLine = editor.Caret.Line
                };

                return(resolver.Resolve(expressionResult, parseInfo, editor.Document.Text));
            }
Example #24
0
 void ParseInformationUpdatedInvoked(ParseInformation parseInfo)
 {
     try {
         textAreaControl.Document.FoldingManager.UpdateFoldings(TitleName, parseInfo);
         UpdateClassMemberBookmarks(parseInfo);
         textAreaControl.ActiveTextAreaControl.TextArea.Refresh(textAreaControl.ActiveTextAreaControl.TextArea.FoldMargin);
         textAreaControl.ActiveTextAreaControl.TextArea.Refresh(textAreaControl.ActiveTextAreaControl.TextArea.IconBarMargin);
     } catch (Exception ex) {
         MessageService.ShowError(ex);
     }
 }
Example #25
0
        public static void ParseViewContent(IViewContent viewContent)
        {
            string           text             = ((IEditable)viewContent).Text;
            ParseInformation parseInformation = ParseFile(viewContent.PrimaryFileName,
                                                          text, !viewContent.PrimaryFile.IsUntitled);

            if (parseInformation != null && viewContent is IParseInformationListener)
            {
                ((IParseInformationListener)viewContent).ParseInformationUpdated(parseInformation);
            }
        }
Example #26
0
        void FetchParseInformation()
        {
            ParseInformation parseInfo = SD.ParserService.GetCachedParseInformation(this.FileName);

            if (parseInfo == null)
            {
                // if parse info is not yet available, start parsing on background
                SD.ParserService.ParseAsync(this.FileName, primaryTextEditorAdapter.Document).FireAndForget();
                // we'll receive the result using the ParseInformationUpdated event
            }
            ParseInformationUpdated(parseInfo);
        }
Example #27
0
        void FetchParseInformation()
        {
            ParseInformation parseInfo = ParserService.GetExistingParseInformation(this.FileName);

            if (parseInfo == null)
            {
                // if parse info is not yet available, start parsing on background
                ParserService.BeginParse(this.FileName, primaryTextEditorAdapter.Document);
                // we'll receive the result using the ParseInformationUpdated event
            }
            ParseInformationUpdated(parseInfo);
        }
Example #28
0
        public void Parse_ClassMethodHasNoPropertyButHasAssignmentStatementUsingMemberExpression_ParseInfoHasNoPropertyAddedAndNoExceptionThrown()
        {
            string code =
                "class MyClass:\r\n" +
                "    a.b = foo()\r\n" +
                "\r\n";

            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);
            int count = parseInfo.CompilationUnit.Classes[0].Properties.Count;

            Assert.AreEqual(0, count);
        }
Example #29
0
        public void Parse_ClassMethodHasNoPropertyButHasAssignmentStatementSetToValueFromFunctionCall_ParseInfoHasNoPropertyAdded()
        {
            string code =
                "class MyClass:\r\n" +
                "    a = foo()\r\n" +
                "\r\n";

            ParseInformation parseInfo = PythonParserHelper.CreateParseInfo(code);
            int count = parseInfo.CompilationUnit.Classes[0].Properties.Count;

            Assert.AreEqual(0, count);
        }
Example #30
0
        void UpdateParseInformation(ParseInformation parseInfo)
        {
            CodeEditor editor = GetActiveTypeScriptCodeEditor();

            if (editor != null)
            {
                if (editor.FileName == parseInfo.FileName)
                {
                    editor.ParseInformationUpdated(parseInfo);
                }
            }
        }
Example #31
0
 public CSharpExpressionFinder(ParseInformation parseInformation)
 {
     this.parseInformation = parseInformation;
     if (parseInformation != null && parseInformation.CompilationUnit != null)
     {
         projectContent = parseInformation.CompilationUnit.ProjectContent;
     }
     else
     {
         projectContent = DefaultProjectContent.DummyProjectContent;
     }
 }
		public VBNetToCSharpConvertVisitor(IProjectContent pc, ParseInformation parseInfo)
		{
			this.resolver = new NRefactoryResolver(LanguageProperties.VBNet);
			this.projectContent = pc;
			this.parseInformation = parseInfo;
		}
		void UpdateParseInformation(ParseInformation parseInfo)
		{
			CodeEditor editor = GetActiveTypeScriptCodeEditor();
			if (editor != null) {
				if (editor.FileName == parseInfo.FileName) {
					editor.ParseInformationUpdated(parseInfo);
				}
			}
		}
		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;
		}
		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, sourceLanguage);
			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(visitor.Cu);
			
			return result;
		}
		protected virtual HashSet<PossibleTypeReference> FindPossibleTypeReferences(IDomProgressMonitor progressMonitor, string fileContent, ParseInformation parseInfo)
		{
			NR.IParser parser = ParseFile(progressMonitor, fileContent);
			if (parser == null) {
				return null;
			} else {
				FindPossibleTypeReferencesVisitor visitor = new FindPossibleTypeReferencesVisitor(parseInfo);
				parser.CompilationUnit.AcceptVisitor(visitor, null);
				parser.Dispose();
				return visitor.list;
			}
		}
			public FindPossibleTypeReferencesVisitor(ParseInformation parseInformation)
			{
				if (parseInformation != null) {
					this.parseInformation = parseInformation;
					resolver = new NRefactoryResolver.NRefactoryResolver(parseInformation.CompilationUnit.ProjectContent.Language);
				}
			}