本文整理汇总了C#中Expression.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# Expression.ToString方法的具体用法?C# Expression.ToString怎么用?C# Expression.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Expression
的用法示例。
在下文中一共展示了Expression.ToString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddDebugInfo
//The following method does not check the validaity of the span
public static Expression AddDebugInfo(Expression expression, SymbolDocumentInfo document, int startLine, int startColumn, int endLine, int endColumn) {
if (expression == null) {
Debug.WriteLine("Null error ding: " + expression.ToString());
throw new System.ArgumentNullException("expression");
}
var sequencePoint = Expression.DebugInfo(document,
startLine, startColumn, endLine, endColumn);
var clearance = Expression.ClearDebugInfo(document);
//always attach a clearance
if (expression.Type == typeof(void)) {
return Expression.Block(
sequencePoint,
expression,
clearance
);
} else {
//save the expression to a variable
var p = Expression.Parameter(expression.Type, null);
return Expression.Block(
new[] { p },
sequencePoint,
Expression.Assign(p, expression),
clearance,
p
);
}
}
示例2: Plot
public static void Plot(Expression f, Variable x, Constant x0, Constant x1)
{
ComputerAlgebra.Plotting.Plot p = new ComputerAlgebra.Plotting.Plot()
{
x0 = (double)x0,
x1 = (double)x1,
Title = f.ToString(),
xLabel = x.ToString(),
};
foreach (Expression i in Set.MembersOf(f))
p.Series.Add(new ComputerAlgebra.Plotting.Function(ExprFunction.New(i, x)) { Name = i.ToString() });
}
示例3: Parse
public void Parse(ref string[] program)
{
_Callee = ParseUtils.GetToken(ref program);
WooScript._Log.AddMsg("Callee : " + _Callee);
string comma = ParseUtils.GetToken(ref program);
if (!comma.Equals(",", StringComparison.Ordinal))
throw new ParseException("Expected \",\"");
_Expr = ExpressionBuilder.Parse(ref program);
if (_Expr.GetExpressionType() != VarType.varFloat)
throw new ParseException("Failed to convert repeat number to float");
WooScript._Log.AddMsg("Repeats : " + _Expr.ToString());
}
示例4: generateExpression
Expression generateExpression()
{
int operand1;
int operand2;
List<string> operators = new List<string>() { "+", "-", "*", "/" };
//int result;
System.Random random = new System.Random();
operand1 = random.Next(0, 100);
operand2 = random.Next(0, 100);
string op = operators[random.Next(0, operators.Count)];
string tempEq = operand1.ToString() + op + operand2.ToString();
Expression exp = new Expression(tempEq);
Debug.Log(exp.ToString());
return exp;
}
示例5: TrRhs
// Invoked typically as TrRhs(variable, null, RhsExpr) <- UpdateStmt with multi-assignment
// or TrRhs(null, LhsExpr, RhsExpr) <- AssignStmt
void TrRhs(BoundVar target, Expression targetExpr, AssignmentRhs rhs)
{
Contract.Requires((target == null) != (targetExpr == null));
var tRhs = rhs as TypeRhs;
if (rhs is HavocRhs) {
// do nothing
}
else {
using (WriteArray()) {
j.WriteValue(KremlinAst.ESequence);
using (WriteArray()) {
WriteEUnit();
// For C#, Dafny calls TrExpr(targetExpr), emits "=" then TrAssignmentRhs(rhs),
// For Kremlin, we may generate EAssign or EBufWrite depending on the
// targetExpr type. The ELet has already been generated by the caller and
// we are inside an ESequence, about to generate the RHS expression code.
if (target != null) {
TrAssignmentRhs(rhs);
}
else {
if (targetExpr is SeqSelectExpr) {
SeqSelectExpr e = (SeqSelectExpr)targetExpr;
Contract.Assert(e.Seq.Type != null);
if (!e.SelectOne) {
WriteEAbort("BUGBUG: TrRhs is a SeqSelectExpr with SelectMany"); // bugbug: is this valid Dafny?
}
else {
using (WriteArray()) {
j.WriteValue(KremlinAst.EBufWrite);
using (WriteArray()) { // of (expr * expr * expr)
TrExpr(e.Seq, false); // expr1 - the buffer identifier
TrBufferIndexSizeExpr(e.E0, false); // expr2 - the buffer offset
TrAssignmentRhs(rhs); // expr3 - the value to write
}
}
}
}
else if (targetExpr is IdentifierExpr) {
using (WriteArray()) {
j.WriteValue(KremlinAst.EAssign);
using (WriteArray()) {
var e = (IdentifierExpr)targetExpr;
WriteEBound(e.Var);
TrAssignmentRhs(rhs);
}
}
}
else if (targetExpr is MemberSelectExpr) {
MemberSelectExpr e = (MemberSelectExpr)targetExpr;
SpecialField sf = e.Member as SpecialField;
if (sf != null) {
WriteEAbort("BUGBUG MemberSelectExpr TrRhs if SpecialField not supported"); // bugbug: implement
}
else {
// EAssign of
// EField(lident, EBufRead( EBound(var), 0), FieldName)
using (WriteArray()) {
j.WriteValue(KremlinAst.EAssign);
using (WriteArray()) { // of (expr * expr)
// EAssign expr1
using (WriteArray()) {
j.WriteValue(KremlinAst.EField);
using (WriteArray()) { // of (lident * expr * ident)
WriteLident(e.Obj.Type);
using (WriteArray()) {
j.WriteValue(KremlinAst.EBufRead);
using (WriteArray()) { // of (expr * expr)
TrExpr(e.Obj, false); // This will generate an EBound reference to the variable
WriteConstant(0u); // expr2 is the offset (always 0)
}
}
j.WriteValue(e.Member.Name);
}
}
TrAssignmentRhs(rhs); // right-hand-side expression
}
}
}
}
else {
WriteEAbort("BUGBUG TrRhs of unsupported targetExpr type " + targetExpr.ToString());
}
}
if (tRhs != null && tRhs.InitCall != null) {
// We have now generated: var target = Default value;
// Generate statement: target.ctor();
var oldEnclosingThis = enclosingThis;
if (target != null) {
j.WriteComment("TrRhs of InitCall to target");
enclosingThis = target;
TrCallStmt(tRhs.InitCall); // expr2
}
else {
// targetExpr should be turned into the enclosingThis
using (WriteArray()) {
string nw = idGenerator.FreshId("_nw");
//.........这里部分代码省略.........
示例6: EvalListAsDotNet
/// <summary>
/// Evaluates a list expression, converting it into an IEnumerable<HeronValue>
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public IEnumerable<HeronValue> EvalListAsDotNet(Expression list)
{
SeqValue sv = Eval(list) as SeqValue;
if (sv == null)
throw new Exception("Expected list: " + list.ToString());
IInternalIndexable ii = sv.GetIndexable();
for (int i = 0; i < ii.InternalCount(); ++i)
yield return ii.InternalAt(i);
}
示例7: GenerateCodeForExpressionWithoutOperator
private void GenerateCodeForExpressionWithoutOperator(Expression expression)
{
System.Diagnostics.Trace.WriteLine(expression.ToString());
ScriptReader reader = new ScriptReader(expression, _source.LineNumber);
Token firstToken = reader.ReadNextToken();
Token memberName = null;
bool staticAccess = false;
if (firstToken.IsVariableType)
{
staticAccess = true;
}
else if (reader.NextIsKeyword(PredefinedSymbol.OpenSquareBracket))
{
Expression arrayIndex = ReadExpression(reader, true, PredefinedSymbol.CloseSquareBracket);
GenerateCodeForExpression(arrayIndex);
// TODO: Array access
}
if (reader.NextIsKeyword(PredefinedSymbol.Dot))
{
if ((firstToken.Type != TokenType.LocalVariable) &&
(firstToken.Type != TokenType.GlobalVariable) &&
(firstToken.Type != TokenType.StructType))
{
throw new CompilerMessage(ErrorCode.ParentIsNotAStruct, "'" + firstToken.Name + "' is not a struct");
}
memberName = reader.ReadNextToken();
// TODO: struct member stuff
if (staticAccess)
{
}
}
else if (staticAccess)
{
throw new CompilerMessage(ErrorCode.InvalidUseOfStruct, "Struct cannot be used in this way");
}
else
{
// TODO: just read the variable itself / execute the function
}
// TODO: Code this
}
示例8: TranslateAssignment
private static SUnit TranslateAssignment(Statement statement)
{
// action = "Assign"
// define left-hand-side (lhs)
// theme = right hand side
var fieldRule = SetupFieldRule();
// var equalsSign = statement.GetDescendants<OperatorUse>()
// .Where(o => o.Text.Equals("=")).First();
// var lhs = equalsSign.GetSiblingsBeforeSelf<VariableUse>().First();
var assignExpression = (VariableDeclaration) statement.GetExpressions().First();
var lhs = assignExpression.Name;
var lhsFieldContext = new FieldContext(assignExpression.VariableType.ToString(), false, "");
var lhsDecNode = new FieldDeclarationNode(lhs.ToString(), lhsFieldContext);
fieldRule.InClass(lhsDecNode);
fieldRule.ConstructSwum(lhsDecNode);
var rhsString = "";
var rhsAction = "";
var rhsTheme = "";
Expression rhs = new Expression();
if (assignExpression.Initializer != null)
{
rhs = assignExpression.Initializer;
}
if (rhs is VariableUse)
{
var rhsFieldContext = new FieldContext(rhs.ResolveType().First().ToString(), false, "");
var rhsDecNode = new FieldDeclarationNode(rhs.ToString(), lhsFieldContext);
fieldRule.InClass(rhsDecNode);
fieldRule.ConstructSwum(rhsDecNode);
rhsAction = "Assign";
rhsString = rhsDecNode.ToPlainString();
}
else if (rhs is MethodCall)
{
string type = rhs.ResolveType().ToString();
MethodContext mc = new MethodContext(type);
MethodDeclarationNode mdn = new MethodDeclarationNode(rhs.ToString(), mc);
var swumRule = SetupBaseVerbRule();
swumRule.InClass(mdn);
swumRule.ConstructSwum(mdn);
rhsAction = mdn.Action.ToPlainString();
rhsTheme = mdn.Action.ToPlainString();
rhsString = mdn.ToPlainString();
}
else
{
rhsString = rhs.ToString();
}
var sunit = new SUnit();
sunit.type = SUnitType.Assignment;
sunit.action = rhsString;
//sunit.lhs = lhsDecNode.ToPlainString();
sunit.lhs = lhs.ToString();
sunit.theme = rhsString;
return sunit;
}
示例9: WithAlia
private string WithAlia(Expression expression)
{
var p = expression as ParameterExpression;
if (p == null) return expression.ToString();
return string.Format(" {0} as {1} ", p.Name, p.Alia);
}
示例10: EvaluateInvocationExpression
private object EvaluateInvocationExpression(Expression expression, List<object> argumentValues, CodeContext codeContext)
{
string invocation = expression.ToString();
object lastObject = codeContext.ContainerInstance;
if (invocation == "System.Math.Max" ||
invocation == "Math.Max")
{
return PrimitiveOperationManager.Self.MaxObjects(argumentValues[0], argumentValues[1]);
}
else if (invocation == "GetFile" && argumentValues.Count == 1)
{
ElementRuntime elementRuntime = null;
// We're going to have to assume the user means to call GetFile from the current element
if (codeContext.ContainerInstance != null)
{
if (codeContext.ContainerInstance is ElementRuntime)
{
elementRuntime = codeContext.ContainerInstance as ElementRuntime;
}
}
if (elementRuntime != null)
{
return elementRuntime.GetReferencedFileSaveRuntime(argumentValues[0] as string);
}
else
{
return null;
}
}
else if (invocation == "System.Math.Min" ||
invocation == "Math.Min")
{
return PrimitiveOperationManager.Self.MinObjects(argumentValues[0], argumentValues[1]);
}
else if (invocation == "InterpolateBetween" || invocation == "this.InterpolateBetween")
{
MethodCallParser.InterpolateBetween(lastObject as ElementRuntime, argumentValues[0], argumentValues[1], argumentValues[2]);
return null;
}
else
{
object caller = GetCaller(expression, codeContext);
MethodInfo methodInfo;
object toReturn = null;
Type[] argumentTypes = new Type[argumentValues.Count];
for (int i = 0; i < argumentValues.Count; i++)
{
if (argumentValues[i] != null)
{
argumentTypes[i] = argumentValues[i].GetType();
}
}
if (TryHandleSpecialCase(expression, argumentValues, argumentTypes, codeContext, invocation, caller, out toReturn))
{
// do nothing, toReturn is set
}
else
{
GetMethodInfo(expression, argumentValues, argumentTypes, codeContext, invocation, caller, out methodInfo);
if (methodInfo != null)
{
toReturn = methodInfo.Invoke(caller, argumentValues.ToArray());
}
}
return toReturn;
}
//else
//{
// throw new NotImplementedException();
//}
}
示例11: RecordExpression
/// <summary>
/// Records information about the given expression, under the given node.
/// </summary>
/// <param name="expression">
/// The expression to record.
/// </param>
/// <param name="parentNode">
/// The Xml node to record this expression beneath.
/// </param>
/// <returns>
/// Returns the new Xml node describing this expression.
/// </returns>
private static XmlNode RecordExpression(Expression expression, XmlNode parentNode)
{
Param.AssertNotNull(expression, "expression");
Param.AssertNotNull(parentNode, "parentNode");
// Create a new node for this expression and add it to the parent.
XmlNode expressionNode = parentNode.OwnerDocument.CreateElement("Expression");
parentNode.AppendChild(expressionNode);
// Add the name and contents of the expression.
if (expression.ExpressionType == ExpressionType.Literal)
{
XmlAttribute text = parentNode.OwnerDocument.CreateAttribute("Text");
text.Value = expression.ToString();
expressionNode.Attributes.Append(text);
}
XmlAttribute type = parentNode.OwnerDocument.CreateAttribute("Type");
type.Value = expression.GetType().Name;
expressionNode.Attributes.Append(type);
return expressionNode;
}
示例12: Solve
/// <summary>
/// Solve the circuit for transient simulation.
/// </summary>
/// <param name="Analysis">Analysis from the circuit to solve.</param>
/// <param name="TimeStep">Discretization timestep.</param>
/// <param name="Log">Where to send output.</param>
/// <returns>TransientSolution describing the solution of the circuit.</returns>
public static TransientSolution Solve(Analysis Analysis, Expression TimeStep, IEnumerable<Arrow> InitialConditions, ILog Log)
{
Expression h = TimeStep;
Log.WriteLine(MessageType.Info, "Building solution for h={0}", TimeStep.ToString());
// Analyze the circuit to get the MNA system and unknowns.
List<Equal> mna = Analysis.Equations.ToList();
List<Expression> y = Analysis.Unknowns.ToList();
LogExpressions(Log, MessageType.Verbose, "System of " + mna.Count + " equations and " + y.Count + " unknowns = {{ " + String.Join(", ", y) + " }}", mna);
// Evaluate for simulation functions.
// Define T = step size.
Analysis.Add("T", h);
// Define d[t] = delta function.
Analysis.Add(ExprFunction.New("d", Call.If((0 <= t) & (t < h), 1, 0), t));
// Define u[t] = step function.
Analysis.Add(ExprFunction.New("u", Call.If(t >= 0, 1, 0), t));
mna = mna.Resolve(Analysis).OfType<Equal>().ToList();
// Find out what variables have differential relationships.
List<Expression> dy_dt = y.Where(i => mna.Any(j => j.DependsOn(D(i, t)))).Select(i => D(i, t)).ToList();
// Find steady state solution for initial conditions.
List<Arrow> initial = InitialConditions.ToList();
Log.WriteLine(MessageType.Info, "Performing steady state analysis...");
SystemOfEquations dc = new SystemOfEquations(mna
// Derivatives, t, and T are zero in the steady state.
.Evaluate(dy_dt.Select(i => Arrow.New(i, 0)).Append(Arrow.New(t, 0), Arrow.New(T, 0)))
// Use the initial conditions from analysis.
.Evaluate(Analysis.InitialConditions)
// Evaluate variables at t=0.
.OfType<Equal>(), y.Select(j => j.Evaluate(t, 0)));
// Solve partitions independently.
foreach (SystemOfEquations i in dc.Partition())
{
try
{
List<Arrow> part = i.Equations.Select(j => Equal.New(j, 0)).NSolve(i.Unknowns.Select(j => Arrow.New(j, 0)));
initial.AddRange(part);
LogExpressions(Log, MessageType.Verbose, "Initial conditions:", part);
}
catch (Exception)
{
Log.WriteLine(MessageType.Warning, "Failed to find partition initial conditions, simulation may be unstable.");
}
}
// Transient analysis of the system.
Log.WriteLine(MessageType.Info, "Performing transient analysis...");
SystemOfEquations system = new SystemOfEquations(mna, dy_dt.Concat(y));
// Solve the diff eq for dy/dt and integrate the results.
system.RowReduce(dy_dt);
system.BackSubstitute(dy_dt);
IEnumerable<Equal> integrated = system.Solve(dy_dt)
.NDIntegrate(t, h, IntegrationMethod.Trapezoid)
// NDIntegrate finds y[t + h] in terms of y[t], we need y[t] in terms of y[t - h].
.Evaluate(t, t - h).Cast<Arrow>()
.Select(i => Equal.New(i.Left, i.Right)).Buffer();
system.AddRange(integrated);
LogExpressions(Log, MessageType.Verbose, "Integrated solutions:", integrated);
LogExpressions(Log, MessageType.Verbose, "Discretized system:", system.Select(i => Equal.New(i, 0)));
// Solving the system...
List<SolutionSet> solutions = new List<SolutionSet>();
// Partition the system into independent systems of equations.
foreach (SystemOfEquations F in system.Partition())
{
// Find linear solutions for y. Linear systems should be completely solved here.
F.RowReduce();
IEnumerable<Arrow> linear = F.Solve();
if (linear.Any())
{
linear = Factor(linear);
solutions.Add(new LinearSolutions(linear));
LogExpressions(Log, MessageType.Verbose, "Linear solutions:", linear);
}
// If there are any variables left, there are some non-linear equations requiring numerical techniques to solve.
if (F.Unknowns.Any())
{
// The variables of this system are the newton iteration updates.
List<Expression> dy = F.Unknowns.Select(i => NewtonIteration.Delta(i)).ToList();
// Compute JxF*dy + F(y0) == 0.
SystemOfEquations nonlinear = new SystemOfEquations(
F.Select(i => i.Gradient(F.Unknowns).Select(j => new KeyValuePair<Expression, Expression>(NewtonIteration.Delta(j.Key), j.Value))
//.........这里部分代码省略.........
示例13: VisitUnknown
protected override string VisitUnknown(Expression E)
{
return Escape(E.ToString());
}
示例14: expression2str_aux
//ll
private static string expression2str_aux(Expression expr) {
if(expr ==null)
return "NULL";
if(expr is TernaryExpression)
{
switch(expr.NodeType)
{
case NodeType.Initblk:
return initblk2str((TernaryExpression) expr);
case NodeType.Cpblk:
return cpblk2str((TernaryExpression) expr);
case NodeType.Conditional:
return "(" + expression2str(((TernaryExpression) expr).Operand1) +
" ? " + expression2str(((TernaryExpression) expr).Operand2) +
" : " + expression2str(((TernaryExpression) expr).Operand3) + ")";
default:
return "(unknown ternary expression type " + expr.NodeType + ")";
}
}
if(expr is BinaryExpression)
return binaryexpr2str((BinaryExpression) expr);
if(expr is UnaryExpression)
return unaryexpr2str((UnaryExpression) expr);
switch (expr.NodeType)
{
case NodeType.Local:
return local2str((Local)expr);
case NodeType.Literal:
return literal2str((Literal)expr);
case NodeType.Parameter:
case NodeType.This:
return parameter2str((Parameter)expr);
case NodeType.MemberBinding:
return memberbinding2str((MemberBinding)expr);
case NodeType.Pop:
if (expr is UnaryExpression)
throw new ApplicationException("this should not occur");
else
return "EPOP";
case NodeType.MethodCall:
case NodeType.Call:
case NodeType.Calli:
case NodeType.Callvirt:
return methodcall2str((MethodCall)expr);
case NodeType.Indexer:
return indexer2str((Indexer)expr);
case NodeType.Construct: // new
return construct2str((Construct)expr);
case NodeType.ConstructArray: // anew
return constructarray2str((ConstructArray)expr);
case NodeType.AddressDereference:
return addrderef2str((AddressDereference)expr);
case NodeType.Quantifier:
return quantifier2str((Quantifier)expr);
case NodeType.OldExpression:
return oldExpression2str((OldExpression)expr);
case NodeType.ReturnValue:
return "result";
default:
//System.Compiler.Node a= base
{
return expr.ToString();
// System.Compiler.SourceContext a = expr.SourceContext;
// string b = a.SourceText;
// return b;
}
}
}
示例15: AddDefinition
/// <summary>
/// Define the value of an expression in the current context.
/// </summary>
/// <param name="Key"></param>
/// <param name="Value"></param>
public void AddDefinition(Expression Key, Expression Value)
{
Expression value;
if (!context.Definitions.TryGetValue(Key, out value))
context.Definitions.Add(Key, Value);
else if (!value.Equals(Value))
throw new ArgumentException("Redefinition of '" + Key.ToString() + "'.");
}