当前位置: 首页>>代码示例>>C#>>正文


C# CSharpParser.Parse方法代码示例

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


在下文中一共展示了CSharpParser.Parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ClassInitialize

        public static void ClassInitialize(TestContext context)
        {
            Token[] psTokens;
            ParseError[] psErrors;
            var ast = Parser.ParseFile(Path.Combine(context.DeploymentDirectory, ExpectationsFile), out psTokens, out psErrors);
            var items = ast.EndBlock.FindAll(m => m is AssignmentStatementAst, false);
            Expectations = new Dictionary<string, string>();

            foreach (AssignmentStatementAst item in items)
            {
                var variableExpression = item.Left as VariableExpressionAst;
                var scriptBlockAst = item.Right.Find(m => m is ScriptBlockAst, true) as ScriptBlockAst;
                if (variableExpression != null && scriptBlockAst != null)
                {
                    Expectations.Add(variableExpression.VariablePath.UserPath, scriptBlockAst.Extent.ToString().Trim('}', '{').Trim());
                }
            }

            TestData = new Dictionary<string, string>();

            var parser = new CSharpParser();
            var syntaxTree = parser.Parse(File.ReadAllText(Path.Combine(context.DeploymentDirectory, TestDataFile)));
            foreach (NamespaceDeclaration namespaceDeclaration in syntaxTree.Members.Where(m => m is NamespaceDeclaration))
            {
                TestData.Add(namespaceDeclaration.FullName, namespaceDeclaration.ToString());
            }
        }
开发者ID:modulexcite,项目名称:PowerShellCodeDomProvider,代码行数:27,代码来源:Test.cs

示例2: Run

		protected override void Run ()
		{
			MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument;
			CSharpParser parser = new CSharpParser ();
			var unit = parser.Parse (doc.Editor);
			if (unit == null)
				return;
			var node = unit.GetNodeAt (doc.Editor.Caret.Line, doc.Editor.Caret.Column);
			if (node == null)
				return;
			Stack<AstNode > nodeStack = new Stack<AstNode> ();
			nodeStack.Push (node);
			if (doc.Editor.IsSomethingSelected) {
				while (node != null && doc.Editor.MainSelection.IsSelected (node.StartLocation.Line, node.StartLocation.Column, node.EndLocation.Line, node.EndLocation.Column)) {
					node = node.Parent;
					if (node != null) {
						if (nodeStack.Count > 0 && nodeStack.Peek ().StartLocation == node.StartLocation && nodeStack.Peek ().EndLocation == node.EndLocation)
							nodeStack.Pop ();
						nodeStack.Push (node);
					}
				}
			}
			
			if (nodeStack.Count > 2) {
				nodeStack.Pop (); // parent
				nodeStack.Pop (); // current node
				node = nodeStack.Pop (); // next children in which the caret is
				doc.Editor.SetSelection (node.StartLocation.Line, node.StartLocation.Column, node.EndLocation.Line, node.EndLocation.Column);
			} else {
				doc.Editor.ClearSelection ();
			}
		}
开发者ID:yayanyang,项目名称:monodevelop,代码行数:32,代码来源:ExpandSelectionHandler.cs

示例3: 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

示例4: 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

示例5: 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

示例6: 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

示例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: 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

示例9: TestCapturedForeachInCSharp4

        public void TestCapturedForeachInCSharp4()
        {
            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, false);

            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.CapturedUnknown, 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

示例10: 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

示例11: ExtractPrototypeAndMethod

        public MethodResult ExtractPrototypeAndMethod(string code)
        {
            Guard.AgainstNullArgument("code", code);

            var @class = "class A { " + code + " } ";
            var visitor = new MethodVisitor();
            var parser = new CSharpParser();
            var syntaxTree = parser.Parse(@class);
            syntaxTree.AcceptVisitor(visitor);
            syntaxTree.Freeze();

            var result = visitor.GetMethodDeclarations().FirstOrDefault();

            // find newlines in method signature to maintain linenumbers
            var newLines = code.Substring(0, code.IndexOf("{", StringComparison.Ordinal) - 1)
                .Where(x => x.Equals('\n'))
                .Aggregate(string.Empty, (a, c) => a + c);

            // use code methodblock to maintain linenumbers
            var codeBlock = code.Substring(code.IndexOf("{", StringComparison.Ordinal), code.LastIndexOf("}", StringComparison.Ordinal) - code.IndexOf("{", StringComparison.Ordinal) + 1);
            var method = result.MethodExpression.ToString();
            var blockStart = method.IndexOf("{", StringComparison.Ordinal);
            var blockEnd = method.LastIndexOf("}", StringComparison.Ordinal);
            method = method.Remove(blockStart, blockEnd - blockStart + 1);
            method = method.Insert(blockStart, codeBlock);

            return new MethodResult
            {
                ProtoType = result.MethodPrototype.ToString().Trim() + newLines,
                MethodExpression = newLines + method.Trim()
            };
        }
开发者ID:AsCloud,项目名称:scriptcs,代码行数:32,代码来源:CodeAnalyzer.cs

示例12: ToKnockoutVm

        public ConvertionResult ToKnockoutVm(string code, TranslateOptions options = null)
        {
            if(options == null)
            {
                options = TranslateOptions.Defaults;
            }

            _log.Debug("Converting code to Knockout VM. Options:\n{0}\nCode:\n{1}", options.ToFormattedJson(), code);

            Func<ConvertionResult, ConvertionResult> exit = r =>
            {
                _log.Debug("Returning Convertion Result: {0}", r.ToFormattedJson());
                return r;
            };

            var result = new ConvertionResult();

            if(code.IsNullOrEmpty())
            {
                result.Success = false;
                result.Message = "No code provided";
                return exit(result);
            }

            // do convertion
            code = code.AddDefaultUsings();
            var visitor = new NRefactoryVisitor(options);
            var textReader = new StringReader(code);
            var parser = new CSharpParser();
            var cu = parser.Parse(textReader, "dummy.cs");

            if(parser.HasErrors)
            {
                var errors = cu.GetErrors();
                var warnings = cu.GetErrors(ErrorType.Warning);
                result.Success = false;
                result.Message = "Error parsing code file.";
                result.Errors.AddRange(errors);
                result.Warnings.AddRange(warnings);
                return exit(result);
            }

            if(parser.HasWarnings)
            {
                var warnings = cu.GetErrors(ErrorType.Warning);
                result.Message = "Parsed code contains warnings!";
                result.Warnings.AddRange(warnings);
            }

            cu.AcceptVisitor(visitor);

            var writter = new KnockoutWritter();
            var convertedCode = writter.Write(visitor.Result, options);

            result.Success = true;
            result.Code = convertedCode;

            return exit(result);
        }
开发者ID:Gutek,项目名称:csharp-to-knockout-vm,代码行数:59,代码来源:NRefactoryCodeConvertion.cs

示例13: Parse

        public ParseResult Parse(string code)
        {
            var result = new ParseResult();

            var parser = new CSharpParser();
            var syntaxTree = parser.Parse(code);
            var codeLines = code.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

            var codeLinesDictionary = new Dictionary<int, Tuple<string, bool>>();
            for (int i = 0; i < codeLines.Length; i++)
            {
                codeLinesDictionary.Add(i, new Tuple<string, bool>(codeLines[i], true));
            }

            var typeMembersTree = parser.ParseTypeMembers(code);

            foreach (var typeMember in typeMembersTree.Where(x => x is TypeDeclaration || x is MethodDeclaration))
            {
                var element = typeMember.GetText();
                if (typeMember is TypeDeclaration)
                {
                    result.Declarations += element;
                }
                //else
                //{
                //    result.Declarations += "public static partial ScriptCsMethod {";
                //    result.Declarations += element;
                //    result.Declarations += "}";
                //}

                for (var i = typeMember.StartLocation.Line - 1; i < typeMember.StartLocation.Line; i++)
                {
                    var oldItem = codeLinesDictionary[i];
                    codeLinesDictionary[i] = new Tuple<string, bool>(oldItem.Item1, false);
                }
            }

            var keysToRemove = codeLinesDictionary.Where(x => x.Value.Item2 == false).Select(i => i.Key);
            keysToRemove.ToList().ForEach(x => codeLinesDictionary.Remove(x));

            foreach (var correct in syntaxTree.Members)
            {
                var element = correct.GetText(); ;
                result.Declarations += element;
            }

            if (syntaxTree.Errors.Any())
            {
                var evalLines = codeLines.Skip(syntaxTree.Errors.First().Region.BeginLine - 1).ToList();
                result.Evaluations += string.Join(Environment.NewLine, evalLines);

                //result.Evaluations = "public void ScriptCsInvoke() {" + Environment.NewLine;
                //result.Evaluations = string.Join(Environment.NewLine, codeLinesDictionary.Select(i => i.Value.Item1));
                //result.Evaluations += Environment.NewLine + "}";
            }

            var evaluationTree = parser.ParseStatements(result.Evaluations);
            return result;
        }
开发者ID:modulexcite,项目名称:scriptcs-engine-mono,代码行数:59,代码来源:SyntaxParser.cs

示例14: AddMethod

        public void AddMethod(string methodCode)
        {
            var parser = new CSharpParser();
            var syntaxTree = parser.Parse("public class Foo{" + methodCode + "}");
            var method = syntaxTree.Children.First().Children.First(x => x is MethodDeclaration).Clone();

            tree.AddChild<EntityDeclaration>((EntityDeclaration)method, Roles.TypeMemberRole);
        }
开发者ID:cmanrus,项目名称:challenge,代码行数:8,代码来源:CSharpClassAst.cs

示例15: ParseAsMethodBody

 private static IEnumerable<AstNode> ParseAsMethodBody(CSharpParser parser, ref string sourceCode)
 {
     sourceCode = ExtraCode.Add(
         before: "unsafe partial class MyClass { void M() { ",
         code: sourceCode,
         after: "}}");
     return parser.Parse(new StringReader(sourceCode), "").Children;
 }
开发者ID:shayanelhami,项目名称:syntaxtame,代码行数:8,代码来源:SinppetParser.cs


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