• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# CSharp.CSharpParser类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ICSharpCode.NRefactory.CSharp.CSharpParser的典型用法代码示例。如果您正苦于以下问题:C# CSharpParser类的具体用法?C# CSharpParser怎么用?C# CSharpParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



CSharpParser类属于ICSharpCode.NRefactory.CSharp命名空间,在下文中一共展示了CSharpParser类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ParseString

		public virtual List<CSClass> ParseString(string data, string filePath, string projectDirectory, IEnumerable<CSClass> existingClassList)
		{
			string relativeFilePath = filePath.Replace(projectDirectory,"");
			if(relativeFilePath.StartsWith("\\"))
			{
				relativeFilePath = relativeFilePath.Substring(1);
			}
			List<CSClass> returnValue = new List<CSClass>(existingClassList ?? new CSClass[]{} );
			var parser = new CSharpParser();
			var compilationUnit = parser.Parse(data, filePath);
			var namespaceNodeList = compilationUnit.Children.Where(i=>i is NamespaceDeclaration);
			foreach(NamespaceDeclaration namespaceNode in namespaceNodeList)
			{
				var typeDeclarationNodeList = namespaceNode.Children.Where(i=>i is TypeDeclaration);
				foreach(TypeDeclaration typeDeclarationNode in typeDeclarationNodeList)
				{
					var classObject = returnValue.SingleOrDefault(i=>i.ClassName == typeDeclarationNode.Name && i.NamespaceName == namespaceNode.FullName);
					if(classObject == null)
					{
						classObject = new CSClass
						{
							NamespaceName = namespaceNode.FullName,
							ClassName = typeDeclarationNode.Name
						};
						returnValue.Add(classObject);
					}
					ClassParser.BuildClass(classObject, typeDeclarationNode, relativeFilePath);
				}
			}
			return returnValue;
		}
开发者ID:mmooney,项目名称:MMDB.UITest,代码行数:31,代码来源:ClassParser.cs


示例2: GetMethodBody

        public static string GetMethodBody(string sourceFilePath, string methodName, int callingLine)
        {
            if (!File.Exists(sourceFilePath))
                return string.Format("{0} file not found.", Path.GetFileName(sourceFilePath));

            try
            {
                var parser = new CSharpParser();
                var syntaxTree = parser.Parse(File.ReadAllText(sourceFilePath));

                var result = syntaxTree.Descendants.OfType<MethodDeclaration>()
                    .FirstOrDefault(y => y.NameToken.Name == methodName && y.EndLocation.Line > callingLine);
                if (result != null)
                {
                    return result.ToString(FormattingOptionsFactory.CreateSharpDevelop()).Trim();
                }

                result = syntaxTree.Descendants.OfType<MethodDeclaration>()
                    .FirstOrDefault(y => y.NameToken.Name == methodName);
                if (result != null)
                {
                    return result.ToString(FormattingOptionsFactory.CreateSharpDevelop()).Trim();
                }
            }
            catch
            {
                return readLines(sourceFilePath, callingLine);
            }

            return readLines(sourceFilePath, callingLine);
        }
开发者ID:yao-yi,项目名称:DNTProfiler,代码行数:31,代码来源:MethodDeclarations.cs


示例3: TestCollectNodes

		public void TestCollectNodes()
		{
			var cu = new CSharpParser().Parse("using System;\nclass Test {\n  int field; // comment\n}");
			CollectNodesVisitor v = new CollectNodesVisitor();
			cu.AcceptVisitor(v);
			Assert.AreEqual(cu.DescendantsAndSelf.ToList(), v.nodes);
		}
开发者ID:sphynx79,项目名称:dotfiles,代码行数:7,代码来源:DepthFirstVisitorTests.cs


示例4: ParseAndWrite

        public void ParseAndWrite(PARSE_TYPE type, string inputText)
        {
            // parse through framework
            SyntaxTree tree = new N.CSharpParser().Parse(inputText);

            // dispatch to visitor
            var defaultVisitor = new NRefactoryVisitor();
            tree.AcceptVisitor(defaultVisitor);

            IEnumerable<CLRType> CLRTypesDetected = defaultVisitor.CLRTypes;
            switch (type)
            {
                case PARSE_TYPE.FIELDS:
                    CLRTypesDetected.ToList().ForEach(clrType => clrType.WriteFieldsUML(m_richSb));
                    break;

                case PARSE_TYPE.PROPERTIES:
                    CLRTypesDetected.ToList().ForEach(clrType => clrType.WritePropertiesUML(m_richSb));
                    break;

                case PARSE_TYPE.METHODS:
                    CLRTypesDetected.ToList().ForEach(clrType => clrType.WriteMethodsUML(m_richSb));
                    break;

                case PARSE_TYPE.ALL:
                    CLRTypesDetected.ToList().ForEach(clrType => clrType.Design(m_richSb));
                    break;

                default:
                    throw new NotSupportedException();

            }
        }
开发者ID:goncalod,项目名称:csharp,代码行数:33,代码来源:NRefactoryCom.cs


示例5: TestCapturedForeachInCSharp5

        public void TestCapturedForeachInCSharp5()
        {
            var parser = new CSharpParser();
            var tree = parser.Parse(@"
            using System;
            class TestClass
            {
            void TestMethod()
            {
            int? accum = 0;
            foreach (var x in new int?[] { 1, 2, 3 }) {
            Action action = () => { x = null; };
            accum += x;
            }
            }
            }
            ", "test.cs");
            Assert.AreEqual(0, tree.Errors.Count);

            var method = tree.Descendants.OfType<MethodDeclaration>().Single();
            var analysis = CreateNullValueAnalysis(tree, method, true);

            var foreachStatement = (ForeachStatement)method.Body.Statements.ElementAt(1);
            var foreachBody = (BlockStatement)foreachStatement.EmbeddedStatement;
            var action = foreachBody.Statements.First();
            var lastStatement = method.Body.Statements.Last();

            Assert.AreEqual(NullValueStatus.Unknown, analysis.GetVariableStatusBeforeStatement(action, "x"));
            Assert.AreEqual(NullValueStatus.CapturedUnknown, analysis.GetVariableStatusAfterStatement(action, "x"));
            Assert.AreEqual(NullValueStatus.Unknown, analysis.GetVariableStatusAfterStatement(lastStatement, "accum"));
        }
开发者ID:porcus,项目名称:NRefactory,代码行数:31,代码来源:NullValueAnalysisTests.cs


示例6: Init

		void Init(string program)
		{
			var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib });
			var cu = new CSharpParser().Parse(new StringReader(program), "program.cs");
			compilation = pc.UpdateProjectContent(null, cu.ToTypeSystem()).CreateCompilation();
			typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault();
		}
开发者ID:KAW0,项目名称:Alter-Native,代码行数:7,代码来源:CSharpDocumentationTests.cs


示例7: GetCSharpClasses

        public static List<CSharpClassAst> GetCSharpClasses(this AssignmentStatementAst ast)
        {
            var result = new List<CSharpClassAst>();

            var parser = new CSharpParser();

            foreach (var str in ast.Right.FindAll(x => x is StringConstantExpressionAst,true))
            {
                var value = ((StringConstantExpressionAst)str).Value;
                var syntaxTree = parser.Parse(value);

                if (!syntaxTree.Errors.Any())
                    foreach (var child in syntaxTree.Children)
                    {
                        var tree = child as TypeDeclaration;
                        if (tree != null)
                        {
                            if (tree.ClassType == ClassType.Class)
                                result.Add(new CSharpClassAst(tree, (StringConstantExpressionAst)str));
                        }
                    }
            }

            return result;
        }
开发者ID:cmanrus,项目名称:challenge,代码行数:25,代码来源:ParamGetterExtensions.cs


示例8: ConvertExpression

		string ConvertExpression(string code)
		{
			CSharpParser parser = new CSharpParser();
			var expr = parser.ParseExpression(code);
			Assert.IsFalse(parser.HasErrors);
			return ConvertExpression(expr);
		}
开发者ID:0xb1dd1e,项目名称:NRefactory,代码行数:7,代码来源:CodeDomConvertVisitorTests.cs


示例9: DoCodeComplete

        public static IEnumerable<ICompletionData> DoCodeComplete(string editorText, int offset) // not the best way to put in the whole string every time
        {
            var doc = new ReadOnlyDocument(editorText);
            var location = doc.GetLocation(offset);

            string parsedText = editorText; // TODO: Why are there different values in test cases?


            var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
            syntaxTree.Freeze();
            var unresolvedFile = syntaxTree.ToTypeSystem();

            var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);

            IProjectContent pctx = new CSharpProjectContent();
            var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value };
            pctx = pctx.AddAssemblyReferences(refs);
            pctx = pctx.AddOrUpdateFiles(unresolvedFile);

            var cmp = pctx.CreateCompilation();

            var resolver3 = unresolvedFile.GetResolver(cmp, location);
            var engine = new CSharpCompletionEngine(doc, mb, new TestCompletionDataFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext);


            engine.EolMarker = Environment.NewLine;
            engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();

            var data = engine.GetCompletionData(offset, controlSpace: false);
            return data;

        }
开发者ID:uluhonolulu,项目名称:QCCodingServices.NET,代码行数:32,代码来源:CodeCompletionUtils.cs


示例10: GetNodesBetween

		public void GetNodesBetween()
		{
			var parser = new CSharpParser();
			var expr = parser.ParseExpression("a*b+c*d");
			var nodes = expr.GetNodesBetween(1, 3, 1, 6).ToList();
			Assert.AreEqual(new[] { "b", "+", "c" }, nodes.Select(n => n.ToString()).ToList());
		}
开发者ID:0xb1dd1e,项目名称:NRefactory,代码行数:7,代码来源:AstTests.cs


示例11: Prepare

		protected void Prepare(string source, bool minimizeNames = true, bool expectErrors = false) {
			IProjectContent project = new CSharpProjectContent();
			var parser = new CSharpParser();

			using (var rdr = new StringReader(source)) {
				var pf = new CSharpUnresolvedFile { FileName = "File.cs" };
				var syntaxTree = parser.Parse(rdr, pf.FileName);
				syntaxTree.AcceptVisitor(new TypeSystemConvertVisitor(pf));
				project = project.AddOrUpdateFiles(pf);
			}
			project = project.AddAssemblyReferences(new[] { Files.Mscorlib });

			_errorReporter = new MockErrorReporter(!expectErrors);

			var compilation = project.CreateCompilation();
			var s = new AttributeStore(compilation, _errorReporter);
			RunAutomaticMetadataAttributeAppliers(s, compilation);
			s.RunAttributeCode();

			Metadata = new MetadataImporter(_errorReporter, compilation, s, new CompilerOptions { MinimizeScript = minimizeNames });

			Metadata.Prepare(compilation.GetAllTypeDefinitions());

			AllErrors = _errorReporter.AllMessages.ToList().AsReadOnly();
			AllErrorTexts = _errorReporter.AllMessages.Select(m => m.FormattedMessage).ToList().AsReadOnly();
			if (expectErrors) {
				Assert.That(AllErrorTexts, Is.Not.Empty, "Compile should have generated errors");
			}
			else {
				Assert.That(AllErrorTexts, Is.Empty, "Compile should not generate errors");
			}

			AllTypes = compilation.MainAssembly.TopLevelTypeDefinitions.SelectMany(SelfAndNested).ToDictionary(t => t.ReflectionName);
		}
开发者ID:ShuntaoChen,项目名称:SaltarelleCompiler,代码行数:34,代码来源:MetadataImporterTestBase.cs


示例12: Main

        static void Main(string[] args)
        {
            var gitPath = ConfigurationManager.AppSettings["GitPath"];
              var gitCommitIterator = new GitCommitIterator(gitPath);
              var gitWorkingCopyCheckout = new GitWorkingCopyCheckout(gitPath);
              var workingCopyPath = args[0];
              var analysisOutputPath = Path.Combine(Environment.CurrentDirectory, "analysis");
              EnsureCleanAnalysisOutput(analysisOutputPath);
              var parser = new CSharpParser();
              foreach (var commit in gitCommitIterator.GetCommits(workingCopyPath)) {
            Console.WriteLine(commit);

            gitWorkingCopyCheckout.CheckoutCommit(workingCopyPath, commit);

            using (var output = File.OpenWrite(
              Path.Combine(
            analysisOutputPath,
            commit.AnalysisOutputFileName))) {
              using (var csvWriter = new StreamWriter(output)) {
            CSharpMethod.WriteCsvHeader(csvWriter);
            foreach (var file in CSharpFile.Enumerate(workingCopyPath, commit)) {
              foreach (var method in file.AnalyzeMethods(parser)) {
                method.WriteAsCsv(csvWriter);
              }
            }
            csvWriter.Flush();
              }
            }
              }
              Console.WriteLine("Yeah, I'm done.");
              Console.ReadLine();
        }
开发者ID:yreynhout,项目名称:sharptemporalgitalyzer,代码行数:32,代码来源:Program.cs


示例13: Main

        public static void Main(string[] args)
        {
            var server = new TcpListener(IPAddress.Loopback, 5556);
            server.Start();
            while (true)
            {
                var newClient = server.AcceptTcpClient();
                Console.WriteLine("Got new client.");
                using (var clientStream = newClient.GetStream())
                {
                    var request = CSharpParseRequest.ParseDelimitedFrom(clientStream);
                    Console.WriteLine("Starting collecting AST for:\n");
                    Console.WriteLine(request.Filename);
                    var parser = new CSharpParser();
                    var csFile = new FileStream(request.Filename, FileMode.Open);
                    var cu = parser.Parse(csFile);
                    var resultBuilder = CSharpParseResult.CreateBuilder();
                    foreach (var child in cu.Children) {
                        var builder = Landman.Rascal.CSharp.Profobuf.AstNode.CreateBuilder();
                        GenerateNode(child, builder);
                        resultBuilder.AddResult(builder);
                    }
                    resultBuilder.Build().WriteDelimitedTo(clientStream);
                    Console.WriteLine("\nFinished");
                }

            }
        }
开发者ID:cwi-swat,项目名称:rascal-csharp,代码行数:28,代码来源:Main.cs


示例14: Parse

		public ParseInformation Parse(FileName fileName, ITextSource fileContent, bool fullParseInformationRequested,
		                              IProject parentProject, CancellationToken cancellationToken)
		{
			var csharpProject = parentProject as CSharpProject;
			
			CSharpParser parser = new CSharpParser(csharpProject != null ? csharpProject.CompilerSettings : null);
			parser.GenerateTypeSystemMode = !fullParseInformationRequested;
			
			SyntaxTree cu = parser.Parse(fileContent, fileName);
			cu.Freeze();
			
			CSharpUnresolvedFile file = cu.ToTypeSystem();
			ParseInformation parseInfo;
			
			if (fullParseInformationRequested)
				parseInfo = new CSharpFullParseInformation(file, fileContent.Version, cu);
			else
				parseInfo = new ParseInformation(file, fileContent.Version, fullParseInformationRequested);
			
			IDocument document = fileContent as IDocument;
			AddCommentTags(cu, parseInfo.TagComments, fileContent, parseInfo.FileName, ref document);
			if (fullParseInformationRequested) {
				if (document == null)
					document = new ReadOnlyDocument(fileContent, parseInfo.FileName);
				((CSharpFullParseInformation)parseInfo).newFoldings = CreateNewFoldings(cu, document);
			}
			
			return parseInfo;
		}
开发者ID:asiazhang,项目名称:SharpDevelop,代码行数:29,代码来源:Parser.cs


示例15: Parse

		IUnresolvedFile Parse(string fileName, string code)
		{
			var parser = new CSharpParser();
			var syntaxTree = parser.Parse(code, fileName);
			Assert.IsFalse(parser.HasErrors);
			return syntaxTree.ToTypeSystem();
		}
开发者ID:Paccc,项目名称:SharpDevelop,代码行数:7,代码来源:NUnitTestProjectFixtureBase.cs


示例16: FindSemanticErrors

        public SemanticErrorsResponse FindSemanticErrors(Request request)
        {
            var clientFilename = request.FileName.ApplyPathReplacementsForClient();
            var project = _solution.ProjectContainingFile(request.FileName);
            project.UpdateFile(request.FileName, request.Buffer);
            var solutionSnapshot = new DefaultSolutionSnapshot(_solution.Projects.Select(i => i.ProjectContent));
            SyntaxTree syntaxTree;
            if(project.CompilerSettings!=null){
            	syntaxTree = new CSharpParser(project.CompilerSettings).Parse(request.Buffer, request.FileName);
            }else{
            	syntaxTree = new CSharpParser().Parse(request.Buffer, request.FileName);
            }
            var resolver = new CSharpAstResolver(solutionSnapshot.GetCompilation(project.ProjectContent), syntaxTree);
            var navigator = new SemanticErrorsNavigator();
            resolver.ApplyNavigator(navigator);
            var errors = navigator.GetErrors()
                .Where(e => ShouldIncludeIssue(e.Message))
                .Select(i => new Error
            {
                FileName = clientFilename,
                Message = i.Message,
                Line = i.StartLocation.Line,
                Column = i.EndLocation.Column,
                EndLine = i.EndLocation.Line,
                EndColumn = i.EndLocation.Column
            });

            return new SemanticErrorsResponse
            {
                Errors = errors,
            };
        }
开发者ID:Reese-D,项目名称:my_emacs,代码行数:32,代码来源:SemanticErrorsHandler.cs


示例17: ConvertStatement

		string ConvertStatement(string code)
		{
			CSharpParser parser = new CSharpParser();
			var expr = parser.ParseStatements(new StringReader(code)).Single();
			Assert.IsFalse(parser.HasErrors);
			return ConvertStatement(expr);
		}
开发者ID:mono-soc-2012,项目名称:NRefactory,代码行数:7,代码来源:CodeDomConvertVisitorTests.cs


示例18: Parse

        public string Parse(PARSE_TYPE type, string inputText)
        {
            // parse through framework
            SyntaxTree tree = new N.CSharpParser().Parse(inputText);

            // dispatch to visitor
            var defaultVisitor = new NRefactoryVisitor();
            tree.AcceptVisitor(defaultVisitor);

            IEnumerable<CLRType> inputTextTypes = defaultVisitor.CLRTypes;
            switch (type)
            {
                case PARSE_TYPE.FIELDS:
                    return inputTextTypes.Aggregate(new StringBuilder(), (sb, clr) => sb.AppendLine(clr.GetFieldsUML())).ToString();

                case PARSE_TYPE.PROPERTIES:
                    return inputTextTypes.Aggregate(new StringBuilder(), (sb, clr) => sb.AppendLine(clr.GetPropertiesUML())).ToString();

                case PARSE_TYPE.METHODS:
                    return inputTextTypes.Aggregate(new StringBuilder(), (sb, clr) => sb.AppendLine(clr.GetMethodsUML())).ToString();

                case PARSE_TYPE.ALL:
                    return inputTextTypes.Aggregate(new StringBuilder(), (sb, clr) => sb.AppendLine(clr.Design())).ToString();

                default:
                    throw new NotSupportedException();

            }
        }
开发者ID:goncalod,项目名称:csharp,代码行数:29,代码来源:NRefactoryCom+(ASUSK550's+conflicted+copy+2015-07-29).cs


示例19: Lookup

		IEntity Lookup(string cref)
		{
			string program = @"using System;
using System.Collections.Generic;
/// <summary/>
class Test {
	int @int;
	void M(int a) {}
	
	void Overloaded(int a) {}
	void Overloaded(string a) {}
	void Overloaded(ref int a) {}
	
	public int this[int index] { get { return 0; } }
	
	public static int operator +(Test a, int b) { return 0; }
	public static implicit operator Test(int a) { return 0; }
	public static implicit operator int(Test a) { return 0; }
}
interface IGeneric<A, B> {
	void Test<T>(ref T[,] a);
}
class Impl<T> : IGeneric<List<string>[,], T> {
	void IGeneric<List<string>[,], T>.Test<X>(ref X[,] a) {}
}";
			
			var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib });
			var cu = new CSharpParser().Parse(new StringReader(program), "program.cs");
			var compilation = pc.UpdateProjectContent(null, cu.ToTypeSystem()).CreateCompilation();
			var typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.Single();
			IEntity entity = typeDefinition.Documentation.ResolveCref(cref);
			Assert.IsNotNull(entity, "ResolveCref() returned null.");
			return entity;
		}
开发者ID:KAW0,项目名称:Alter-Native,代码行数:34,代码来源:CSharpCrefLookupTests.cs


示例20: CheckSyntax

		public static bool CheckSyntax(string expression, out Error[] errors)
		{
			var p = new CSharpParser();
			p.ParseExpression(expression);
			errors = p.Errors.ToArray();
			return !errors.Any();
		}
开发者ID:dgrunwald,项目名称:SharpDevelop,代码行数:7,代码来源:DebuggerDotCompletion.cs



注:本文中的ICSharpCode.NRefactory.CSharp.CSharpParser类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# CSharp.EntityDeclaration类代码示例发布时间:2022-05-26
下一篇:
C# CSharp.CSharpOutputVisitor类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap