本文整理汇总了C#中ICSharpCode.NRefactory.CSharp.CSharpParser类的典型用法代码示例。如果您正苦于以下问题:C# CSharpParser类的具体用法?C# CSharpParser怎么用?C# CSharpParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CSharpParser类属于ICSharpCode.NRefactory.CSharp命名空间,在下文中一共展示了CSharpParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
示例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);
}
示例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);
}
示例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();
}
}
示例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"));
}
示例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();
}
示例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;
}
示例8: ConvertExpression
string ConvertExpression(string code)
{
CSharpParser parser = new CSharpParser();
var expr = parser.ParseExpression(code);
Assert.IsFalse(parser.HasErrors);
return ConvertExpression(expr);
}
示例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;
}
示例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());
}
示例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);
}
示例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();
}
示例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");
}
}
}
示例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;
}
示例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();
}