本文整理汇总了C#中ICSharpCode.NRefactory.CSharp.CSharpParser.ParseStatements方法的典型用法代码示例。如果您正苦于以下问题:C# CSharpParser.ParseStatements方法的具体用法?C# CSharpParser.ParseStatements怎么用?C# CSharpParser.ParseStatements使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ICSharpCode.NRefactory.CSharp.CSharpParser
的用法示例。
在下文中一共展示了CSharpParser.ParseStatements方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
示例2: GetVariableDeclarationForLinqMethods
public static VariableInitializer GetVariableDeclarationForLinqMethods(string query, bool requiresSelectNewAnonymousType)
{
try
{
var parser = new CSharpParser();
var block = parser.ParseStatements(ToQueryStatement(query)).ToList();
if (block.Count == 0 || parser.HasErrors)
{
var errs = string.Join(Environment.NewLine, parser.Errors.Select(x => x.Region + ": " + x.ErrorType + " - " + x.Message));
throw new InvalidOperationException("Could not understand query: \r\n" + errs);
}
var declaration = block[0] as VariableDeclarationStatement;
if (declaration == null)
throw new InvalidOperationException("Only local variable declaration are allowed");
if (declaration.Variables.Count != 1)
throw new InvalidOperationException("Only one variable declaration is allowed");
var variable = declaration.Variables.First();
if (variable.Initializer as InvocationExpression == null)
throw new InvalidOperationException("Variable declaration must have an initializer which is a method invocation expression");
var targetObject = ((InvocationExpression)variable.Initializer).Target as MemberReferenceExpression;
if (targetObject == null)
throw new InvalidOperationException("Variable initializer must be invoked on a method reference expression");
if (targetObject.MemberName != "Select" && targetObject.MemberName != "SelectMany")
throw new InvalidOperationException("Variable initializer must end with a select call");
var lambdaExpression = AsLambdaExpression(((InvocationExpression)variable.Initializer).Arguments.Last());
if (lambdaExpression == null)
throw new InvalidOperationException("Variable initializer select must have a lambda expression");
variable.AcceptVisitor(new TransformNullCoalescingOperatorTransformer(), null);
variable.AcceptVisitor(new DynamicExtensionMethodsTranslator(), null);
variable.AcceptVisitor(new TransformDynamicLambdaExpressions(), null);
variable.AcceptVisitor(new TransformDynamicInvocationExpressions(), null);
variable.AcceptVisitor(new TransformObsoleteMethods(), null);
var expressionBody = GetAnonymousCreateExpression(lambdaExpression.Body);
var anonymousTypeCreateExpression = expressionBody as AnonymousTypeCreateExpression;
if (anonymousTypeCreateExpression == null && requiresSelectNewAnonymousType)
throw new InvalidOperationException("Variable initializer select must have a lambda expression with an object create expression");
var objectCreateExpression = expressionBody as ObjectCreateExpression;
if (objectCreateExpression != null && requiresSelectNewAnonymousType)
throw new InvalidOperationException("Variable initializer select must have a lambda expression creating an anonymous type but returning " + objectCreateExpression.Type);
return variable;
}
catch (Exception e)
{
throw new InvalidOperationException("Could not understand query: " + e.Message, e);
}
}
示例3: GetVariableDeclarationForLinqQuery
public static VariableInitializer GetVariableDeclarationForLinqQuery(string query, bool requiresSelectNewAnonymousType)
{
try
{
var parser = new CSharpParser();
var block = parser.ParseStatements(ToQueryStatement(query)).ToList();
if (block.Count == 0 || parser.HasErrors)
{
var errs = string.Join(Environment.NewLine, parser.Errors.Select(x => x.Region + ": " + x.ErrorType + " - " + x.Message));
throw new InvalidOperationException("Could not understand query: \r\n" + errs);
}
var declaration = block[0] as VariableDeclarationStatement;
if (declaration == null)
throw new InvalidOperationException("Only local variable declaration are allowed");
if (declaration.Variables.Count != 1)
throw new InvalidOperationException("Only one variable declaration is allowed");
var variable = declaration.Variables.First();
if (variable.Initializer == null)
throw new InvalidOperationException("Variable declaration must have an initializer");
var queryExpression = (variable.Initializer as QueryExpression);
if (queryExpression == null)
throw new InvalidOperationException("Variable initializer must be a query expression");
var selectClause = queryExpression.Clauses.OfType<QuerySelectClause>().FirstOrDefault();
if (selectClause == null)
throw new InvalidOperationException("Variable initializer must be a select query expression");
var createExpression = GetAnonymousCreateExpression(selectClause.Expression) as AnonymousTypeCreateExpression;
if ((createExpression == null) && requiresSelectNewAnonymousType)
throw new InvalidOperationException(
"Variable initializer must be a select query expression returning an anonymous object");
variable.AcceptVisitor(new TransformNullCoalescingOperatorTransformer(), null);
variable.AcceptVisitor(new DynamicExtensionMethodsTranslator(), null);
variable.AcceptVisitor(new TransformDynamicLambdaExpressions(), null);
variable.AcceptVisitor(new TransformDynamicInvocationExpressions(), null);
variable.AcceptVisitor(new TransformObsoleteMethods(), null);
return variable;
}
catch (Exception e)
{
throw new InvalidOperationException("Could not understand query: " + e.Message, e);
}
}
示例4: ConvertStatement
string ConvertStatement(string code)
{
CSharpParser parser = new CSharpParser();
var expr = parser.ParseStatements(code).Single();
Assert.IsFalse(parser.HasErrors);
return ConvertStatement(expr);
}
示例5: ApplyLine
private void ApplyLine(string line, CodeContext codeContext, string[] allLines, string fileName, ref int index)
{
bool succeeded = true;
mParserLog.AppendLine("--- " + line + " ---");
if (string.IsNullOrEmpty(line))
{
// do nothing
// This may be empty
// because the split function
// may have returned a line with
// only a newline character. If so
// that becomes an empty line when trim
// is called on it. This could be a line
// that was trimmed which is now empty.
}
else if (line.Trim().StartsWith("//"))
{
// comment, carry on
}
else if (line.Trim().StartsWith("#region") || line.Trim().StartsWith("#endregion"))
{
// we can skip region blocks
}
else if (ConditionalCodeBlock.GetBlockTypeStartingAt(allLines, index) != BlockType.None)
{
ElementRuntime elementRuntime = codeContext.ContainerInstance as ElementRuntime;
IElement element = null;
if (elementRuntime != null)
{
element = elementRuntime.AssociatedIElement;
}
succeeded = ApplyConditionalBlocks(allLines, element, codeContext, fileName, ref index);
if (!succeeded)
{
throw new Exception();
}
}
else
{
// here we want to identify how many lines make up the statement since
// it could be something like
// this.X = 3
// + 4;
int numberOfLinesInStatement = GetNumberOfLinesInRegularStatement(allLines, index);
string combined = CombineLines(allLines, index, numberOfLinesInStatement);
string trimmedCombined = combined.Trim();
if (trimmedCombined.StartsWith("{") && trimmedCombined.EndsWith("}"))
{
combined = trimmedCombined.Substring(1, trimmedCombined.Length - 2);
}
CSharpParser parser = new CSharpParser();
var statements = parser.ParseStatements(combined);
// I can be incremented by this function by the number of lines.
// If this value is incremented, then the calling function is responsible
// for recognizing that in its loop and acting properly. The calling function
// assumes an increment of 1 so we won't do anything if there's only 1 line in this
// statement.
if (numberOfLinesInStatement != 1)
{
index += numberOfLinesInStatement;
}
foreach (var statement in statements)
{
if (statement is ExpressionStatement)
{
Expression expression = ((ExpressionStatement)statement).Expression;
if (expression is InvocationExpression || expression is UnaryOperatorExpression)
{
mExpressionParser.EvaluateExpression(expression, codeContext);
}
else if (expression is AssignmentExpression)
{
succeeded = ApplyAssignmentLine(expression as AssignmentExpression, codeContext);
if (!succeeded)
{
throw new Exception();
}
}
else if (expression is IdentifierExpression || expression is MemberReferenceExpression)
{
// This is probably an incomplete line, so let's tolerate it and move on...
}
else
{
throw new Exception();
}
//.........这里部分代码省略.........
示例6: FormatCSharpStatements
protected string FormatCSharpStatements(string code)
{
var parser = new CSharpParser();
parser.ParseStatements(code);
if (parser.HasErrors)
{
var errors = string.Join(Environment.NewLine, parser.Errors.Select(err => err.Message));
throw new TemplateParseException(null, string.Format("{0}{1}{2}", code, Environment.NewLine, errors));
}
return code;
}