protected virtual void WriteObjectInitializer(IEnumerable <Expression> expressions, bool changeCase, TypeDefinition type) { bool needComma = false; List <string> names = new List <string>(); if (expressions != null) { foreach (Expression item in expressions) { NamedExpression namedExression = item as NamedExpression; NamedArgumentExpression namedArgumentExpression = item as NamedArgumentExpression; if (needComma) { this.WriteComma(); } needComma = true; string name = namedExression != null ? namedExression.Name : namedArgumentExpression.Name; if (changeCase) { name = Object.Net.Utilities.StringUtils.ToLowerCamelCase(name); } Expression expression = namedExression != null ? namedExression.Expression : namedArgumentExpression.Expression; this.Write(name, ": "); expression.AcceptVisitor(this.Emitter); names.Add(name); } } if (this.Emitter.Validator.IsObjectLiteral(type) && !this.Emitter.Validator.IsIgnoreType(type)) { var key = BridgeTypes.GetTypeDefinitionKey(type); var tinfo = this.Emitter.Types.FirstOrDefault(t => t.Key == key); if (tinfo != null) { var members = tinfo.InstanceConfig.Fields.Concat(tinfo.InstanceConfig.Properties); if (members.Any()) { foreach (var member in members) { var name = member.GetName(this.Emitter); if (changeCase) { name = Object.Net.Utilities.StringUtils.ToLowerCamelCase(name); } if (names.Contains(name)) { continue; } if (needComma) { this.WriteComma(); } needComma = true; this.Write(name, ": "); var primitiveExpr = member.Initializer as PrimitiveExpression; if (primitiveExpr != null && primitiveExpr.Value is AstType) { this.Write("new " + BridgeTypes.ToJsName((AstType)primitiveExpr.Value, this.Emitter) + "()"); } else { member.Initializer.AcceptVisitor(this.Emitter); } } } } } }
protected virtual void WriteObjectInitializer(IEnumerable <Expression> expressions, bool preserveMemberCase, TypeDefinition type, InvocationResolveResult rr) { bool needComma = false; List <string> names = new List <string>(); if (expressions != null) { foreach (Expression item in expressions) { NamedExpression namedExression = item as NamedExpression; NamedArgumentExpression namedArgumentExpression = item as NamedArgumentExpression; if (needComma) { this.WriteComma(); } needComma = true; string name = namedExression != null ? namedExression.Name : namedArgumentExpression.Name; if (!preserveMemberCase) { name = Object.Net.Utilities.StringUtils.ToLowerCamelCase(name); } Expression expression = namedExression != null ? namedExression.Expression : namedArgumentExpression.Expression; this.Write(name, ": "); expression.AcceptVisitor(this.Emitter); names.Add(name); } } if (this.Emitter.Validator.IsObjectLiteral(type)) { var key = BridgeTypes.GetTypeDefinitionKey(type); var tinfo = this.Emitter.Types.FirstOrDefault(t => t.Key == key); if (tinfo == null) { return; } var itype = tinfo.Type as ITypeDefinition; var mode = 0; if (rr != null) { if (rr.Member.Parameters.Count == 1 && rr.Member.Parameters.First().Type.FullName == "Bridge.DefaultValueMode") { var arg = rr.Arguments.FirstOrDefault(); if (arg != null && arg.ConstantValue != null) { mode = (int)arg.ConstantValue; } } else if (itype != null) { var attr = this.Emitter.Validator.GetAttribute(itype.Attributes, Translator.Bridge_ASSEMBLY + ".ObjectLiteralAttribute"); if (attr.PositionalArguments.Count > 0) { var value = attr.PositionalArguments.First().ConstantValue; if (value != null && value is int) { mode = (int)value; } } } } if (mode != 0) { var members = tinfo.InstanceConfig.Fields.Concat(tinfo.InstanceConfig.Properties); if (members.Any()) { foreach (var member in members) { if (mode == 1 && (member.VarInitializer == null || member.VarInitializer.Initializer.IsNull)) { continue; } var name = member.GetName(this.Emitter); if (!preserveMemberCase) { name = Object.Net.Utilities.StringUtils.ToLowerCamelCase(name); } if (names.Contains(name)) { continue; } if (needComma) { this.WriteComma(); } needComma = true; this.Write(name, ": "); var primitiveExpr = member.Initializer as PrimitiveExpression; if (primitiveExpr != null && primitiveExpr.Value is AstType) { this.Write("new " + BridgeTypes.ToJsName((AstType)primitiveExpr.Value, this.Emitter) + "()"); } else { member.Initializer.AcceptVisitor(this.Emitter); } } } } } }
public virtual void VisitNamedExpression (NamedExpression namedExpression) { VisitChildren (namedExpression); }
bool TryRemoveTransparentIdentifier(QueryExpression query, QueryFromClause fromClause, QueryExpression innerQuery) { if (!IsTransparentIdentifier(fromClause.Identifier)) { return(false); } Match match = selectTransparentIdentifierPattern.Match(innerQuery.Clauses.Last()); if (!match.Success) { return(false); } QuerySelectClause selectClause = (QuerySelectClause)innerQuery.Clauses.Last(); NamedExpression nae1 = match.Get <NamedExpression>("nae1").SingleOrDefault(); NamedExpression nae2 = match.Get <NamedExpression>("nae2").SingleOrDefault(); if (nae1 != null && nae1.Name != ((IdentifierExpression)nae1.Expression).Identifier) { return(false); } Expression nae2Expr = match.Get <Expression>("nae2Expr").Single(); IdentifierExpression nae2IdentExpr = nae2Expr as IdentifierExpression; if (nae2IdentExpr != null && (nae2 == null || nae2.Name == nae2IdentExpr.Identifier)) { // from * in (from x in ... select new { x = x, y = y }) ... // => // from x in ... ... fromClause.Remove(); selectClause.Remove(); // Move clauses from innerQuery to query QueryClause insertionPos = null; foreach (var clause in innerQuery.Clauses) { query.Clauses.InsertAfter(insertionPos, insertionPos = clause.Detach()); } } else { // from * in (from x in ... select new { x = x, y = expr }) ... // => // from x in ... let y = expr ... fromClause.Remove(); selectClause.Remove(); // Move clauses from innerQuery to query QueryClause insertionPos = null; foreach (var clause in innerQuery.Clauses) { query.Clauses.InsertAfter(insertionPos, insertionPos = clause.Detach()); } string ident; if (nae2 != null) { ident = nae2.Name; } else if (nae2Expr is IdentifierExpression) { ident = ((IdentifierExpression)nae2Expr).Identifier; } else if (nae2Expr is MemberReferenceExpression) { ident = ((MemberReferenceExpression)nae2Expr).MemberName; } else { throw new InvalidOperationException("Could not infer name from initializer in AnonymousTypeCreateExpression"); } query.Clauses.InsertAfter(insertionPos, new QueryLetClause { Identifier = ident, Expression = nae2Expr.Detach() }); } return(true); }
public virtual void VisitNamedExpression(NamedExpression namedExpression) { if (this.ThrowException) { throw (Exception)this.CreateException(namedExpression); } }
void AddConvertCollectionOrObjectInitializers (Expression init, CollectionOrObjectInitializers minit) { var initLoc = LocationsBag.GetLocations (minit); var commaLoc = LocationsBag.GetLocations (minit.Initializers); int curComma = 0; if (initLoc != null) init.AddChild (new CSharpTokenNode (Convert (initLoc [0]), 1), ArrayInitializerExpression.Roles.LBrace); foreach (var expr in minit.Initializers) { var collectionInit = expr as CollectionElementInitializer; if (collectionInit != null) { var parent = new ArrayInitializerExpression (); var braceLocs = LocationsBag.GetLocations (expr); if (braceLocs != null) parent.AddChild (new CSharpTokenNode (Convert (braceLocs [0]), 1), ArrayInitializerExpression.Roles.LBrace); for (int i = 0; i < collectionInit.Arguments.Count; i++) { var arg = collectionInit.Arguments [i] as CollectionElementInitializer.ElementInitializerArgument; if (arg == null) continue; parent.AddChild ((ICSharpCode.NRefactory.CSharp.Expression)arg.Expr.Accept (this), ArrayInitializerExpression.Roles.Expression); } if (braceLocs != null) parent.AddChild (new CSharpTokenNode (Convert (braceLocs [1]), 1), ArrayInitializerExpression.Roles.RBrace); init.AddChild (parent, ArrayInitializerExpression.Roles.Expression); } else { var eleInit = expr as ElementInitializer; if (eleInit != null) { var nexpr = new NamedExpression (); nexpr.AddChild (Identifier.Create (eleInit.Name, Convert (eleInit.Location)), NamedArgumentExpression.Roles.Identifier); var assignLoc = LocationsBag.GetLocations (eleInit); if (assignLoc != null) nexpr.AddChild (new CSharpTokenNode (Convert (assignLoc [0]), 1), NamedArgumentExpression.Roles.Assign); if (eleInit.Source != null) { if (eleInit.Source is CollectionOrObjectInitializers) { var arrInit = new ArrayInitializerExpression (); AddConvertCollectionOrObjectInitializers (arrInit, eleInit.Source as CollectionOrObjectInitializers); nexpr.AddChild (arrInit, NamedArgumentExpression.Roles.Expression); } else { nexpr.AddChild ((Expression)eleInit.Source.Accept (this), NamedArgumentExpression.Roles.Expression); } } init.AddChild (nexpr, ArrayInitializerExpression.Roles.Expression); } } if (commaLoc != null && curComma < commaLoc.Count) init.AddChild (new CSharpTokenNode (Convert (commaLoc [curComma++]), 1), ArrayInitializerExpression.Roles.Comma); } if (initLoc != null) { if (initLoc.Count == 3) // optional comma init.AddChild (new CSharpTokenNode (Convert (initLoc [1]), 1), ArrayInitializerExpression.Roles.Comma); init.AddChild (new CSharpTokenNode (Convert (initLoc [initLoc.Count - 1]), 1), ArrayInitializerExpression.Roles.RBrace); } }
protected internal Expression VisitNamedExpression(NamedExpression namedExpression) { return(namedExpression.Update(namedExpression.Expression)); }
public NameBlock(IEmitter emitter, NamedExpression namedExpression) : this(emitter, namedExpression.Name, namedExpression, namedExpression.Expression) { }
/// <summary>Replaces a user-defined function</summary> /// <returns>successful operation</returns> /// <exception cref="MightyCalcException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task ReplaceFunctionAsync(NamedExpression body = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/func"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("PUT"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { return; } else if (status_ == "400") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new MightyCalcException("Invalid expression provided", (int)response_.StatusCode, responseData_, headers_, null); } else if (status_ == "422") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new MightyCalcException("Expression contains unknown functions", (int)response_.StatusCode, responseData_, headers_, null); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new MightyCalcException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
public NamedExpression(NamedExpression expression) : base(expression) { Name = expression.Name; }
public UnifiedElement VisitNamedExpression( NamedExpression namedExpression, object data) { throw new NotImplementedException(); }
public Node VisitNamedExpression(NamedExpression namedExpression) { return(CreateDummy(namedExpression)); }
public void VisitNamedExpression(NamedExpression namedExpression) { JsonObject expression = CreateJsonExpression(namedExpression); expression.AddJsonValue("identifier", GetIdentifier(namedExpression.NameToken)); expression.AddJsonValue("expression", GenExpression(namedExpression.Expression)); Push(expression); }
AstNode TransformByteCode(ILExpression byteCode) { object operand = byteCode.Operand; AstType operandAsTypeRef = AstBuilder.ConvertType(operand as ITypeDefOrRef); List<Expression> args = new List<Expression>(); foreach(ILExpression arg in byteCode.Arguments) { args.Add((Expression)TransformExpression(arg)); } Expression arg1 = args.Count >= 1 ? args[0] : null; Expression arg2 = args.Count >= 2 ? args[1] : null; Expression arg3 = args.Count >= 3 ? args[2] : null; switch (byteCode.Code) { #region Arithmetic case ILCode.Add: case ILCode.Add_Ovf: case ILCode.Add_Ovf_Un: { BinaryOperatorExpression boe; if (byteCode.InferredType is PtrSig) { boe = new BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2); if (byteCode.Arguments[0].ExpectedType is PtrSig || byteCode.Arguments[1].ExpectedType is PtrSig) { boe.AddAnnotation(IntroduceUnsafeModifier.PointerArithmeticAnnotation); } } else { boe = new BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2); } boe.AddAnnotation(byteCode.Code == ILCode.Add ? AddCheckedBlocks.UncheckedAnnotation : AddCheckedBlocks.CheckedAnnotation); return boe; } case ILCode.Sub: case ILCode.Sub_Ovf: case ILCode.Sub_Ovf_Un: { BinaryOperatorExpression boe; if (byteCode.InferredType is PtrSig) { boe = new BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2); if (byteCode.Arguments[0].ExpectedType is PtrSig) { boe.WithAnnotation(IntroduceUnsafeModifier.PointerArithmeticAnnotation); } } else { boe = new BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2); } boe.AddAnnotation(byteCode.Code == ILCode.Sub ? AddCheckedBlocks.UncheckedAnnotation : AddCheckedBlocks.CheckedAnnotation); return boe; } case ILCode.Div: return new BinaryOperatorExpression(arg1, BinaryOperatorType.Divide, arg2); case ILCode.Div_Un: return new BinaryOperatorExpression(arg1, BinaryOperatorType.Divide, arg2); case ILCode.Mul: return new BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2).WithAnnotation(AddCheckedBlocks.UncheckedAnnotation); case ILCode.Mul_Ovf: return new BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2).WithAnnotation(AddCheckedBlocks.CheckedAnnotation); case ILCode.Mul_Ovf_Un: return new BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2).WithAnnotation(AddCheckedBlocks.CheckedAnnotation); case ILCode.Rem: return new BinaryOperatorExpression(arg1, BinaryOperatorType.Modulus, arg2); case ILCode.Rem_Un: return new BinaryOperatorExpression(arg1, BinaryOperatorType.Modulus, arg2); case ILCode.And: return new BinaryOperatorExpression(arg1, BinaryOperatorType.BitwiseAnd, arg2); case ILCode.Or: return new BinaryOperatorExpression(arg1, BinaryOperatorType.BitwiseOr, arg2); case ILCode.Xor: return new BinaryOperatorExpression(arg1, BinaryOperatorType.ExclusiveOr, arg2); case ILCode.Shl: return new BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftLeft, arg2); case ILCode.Shr: return new BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2); case ILCode.Shr_Un: return new BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2); case ILCode.Neg: return new UnaryOperatorExpression(UnaryOperatorType.Minus, arg1).WithAnnotation(AddCheckedBlocks.UncheckedAnnotation); case ILCode.Not: return new UnaryOperatorExpression(UnaryOperatorType.BitNot, arg1); case ILCode.PostIncrement: case ILCode.PostIncrement_Ovf: case ILCode.PostIncrement_Ovf_Un: { if (arg1 is DirectionExpression) arg1 = ((DirectionExpression)arg1).Expression.Detach(); var uoe = new UnaryOperatorExpression( (int)byteCode.Operand > 0 ? UnaryOperatorType.PostIncrement : UnaryOperatorType.PostDecrement, arg1); uoe.AddAnnotation((byteCode.Code == ILCode.PostIncrement) ? AddCheckedBlocks.UncheckedAnnotation : AddCheckedBlocks.CheckedAnnotation); return uoe; } #endregion #region Arrays case ILCode.Newarr: { var ace = new ArrayCreateExpression(); ace.Type = operandAsTypeRef; ComposedType ct = operandAsTypeRef as ComposedType; if (ct != null) { // change "new (int[,])[10] to new int[10][,]" ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers); } if (byteCode.Code == ILCode.InitArray) { ace.Initializer = new ArrayInitializerExpression(); ace.Initializer.Elements.AddRange(args); } else { ace.Arguments.Add(arg1); } return ace; } case ILCode.InitArray: { var ace = new ArrayCreateExpression(); ace.Type = operandAsTypeRef; ComposedType ct = operandAsTypeRef as ComposedType; var arrayType = (ArraySigBase)((ITypeDefOrRef)operand).ToTypeSig(); ; if (ct != null) { // change "new (int[,])[10] to new int[10][,]" ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers); ace.Initializer = new ArrayInitializerExpression(); } var newArgs = new List<Expression>(); if (arrayType is ArraySig) { foreach (var size in arrayType.GetSizes().Skip(1).Reverse()) { int length = (int)size; for (int j = 0; j < args.Count; j += length) { var child = new ArrayInitializerExpression(); child.Elements.AddRange(args.GetRange(j, length)); newArgs.Add(child); } var temp = args; args = newArgs; newArgs = temp; newArgs.Clear(); } } ace.Initializer.Elements.AddRange(args); return ace; } case ILCode.Ldlen: return arg1.Member("Length").WithAnnotation(GetArrayLengthRef()); case ILCode.Ldelem_I: case ILCode.Ldelem_I1: case ILCode.Ldelem_I2: case ILCode.Ldelem_I4: case ILCode.Ldelem_I8: case ILCode.Ldelem_U1: case ILCode.Ldelem_U2: case ILCode.Ldelem_U4: case ILCode.Ldelem_R4: case ILCode.Ldelem_R8: case ILCode.Ldelem_Ref: case ILCode.Ldelem_Any: return arg1.Indexer(arg2); case ILCode.Ldelema: return MakeRef(arg1.Indexer(arg2)); case ILCode.Stelem_I: case ILCode.Stelem_I1: case ILCode.Stelem_I2: case ILCode.Stelem_I4: case ILCode.Stelem_I8: case ILCode.Stelem_R4: case ILCode.Stelem_R8: case ILCode.Stelem_Ref: case ILCode.Stelem_Any: return new AssignmentExpression(arg1.Indexer(arg2), arg3); case ILCode.CompoundAssignment: { CastExpression cast = arg1 as CastExpression; var boe = cast != null ? (BinaryOperatorExpression)cast.Expression : arg1 as BinaryOperatorExpression; // AssignmentExpression doesn't support overloaded operators so they have to be processed to BinaryOperatorExpression if (boe == null) { var tmp = new ParenthesizedExpression(arg1); ReplaceMethodCallsWithOperators.ProcessInvocationExpression((InvocationExpression)arg1); boe = (BinaryOperatorExpression)tmp.Expression; } var assignment = new AssignmentExpression { Left = boe.Left.Detach(), Operator = ReplaceMethodCallsWithOperators.GetAssignmentOperatorForBinaryOperator(boe.Operator), Right = boe.Right.Detach() }.CopyAnnotationsFrom(boe); // We do not mark the resulting assignment as RestoreOriginalAssignOperatorAnnotation, because // the operator cannot be translated back to the expanded form (as the left-hand expression // would be evaluated twice, and might have side-effects) if (cast != null) { cast.Expression = assignment; return cast; } else { return assignment; } } #endregion #region Comparison case ILCode.Ceq: return new BinaryOperatorExpression(arg1, BinaryOperatorType.Equality, arg2); case ILCode.Cne: return new BinaryOperatorExpression(arg1, BinaryOperatorType.InEquality, arg2); case ILCode.Cgt: return new BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2); case ILCode.Cgt_Un: { // can also mean Inequality, when used with object references var arg1Type = byteCode.Arguments[0].InferredType; if (arg1Type != null && !arg1Type.IsValueType) goto case ILCode.Cne; // when comparing signed integral values using Cgt_Un with 0 // the Ast should actually contain InEquality since "(uint)a > 0u" is identical to "a != 0" if (arg1Type.IsSignedIntegralType()) { var p = arg2 as PrimitiveExpression; if (p != null && p.Value.IsZero()) goto case ILCode.Cne; } goto case ILCode.Cgt; } case ILCode.Cle_Un: { // can also mean Equality, when used with object references var arg1Type = byteCode.Arguments[0].InferredType; if (arg1Type != null && !arg1Type.IsValueType) goto case ILCode.Ceq; // when comparing signed integral values using Cle_Un with 0 // the Ast should actually contain Equality since "(uint)a <= 0u" is identical to "a == 0" if (arg1Type.IsSignedIntegralType()) { var p = arg2 as PrimitiveExpression; if (p != null && p.Value.IsZero()) goto case ILCode.Ceq; } goto case ILCode.Cle; } case ILCode.Cle: return new BinaryOperatorExpression(arg1, BinaryOperatorType.LessThanOrEqual, arg2); case ILCode.Cge_Un: case ILCode.Cge: return new BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThanOrEqual, arg2); case ILCode.Clt_Un: case ILCode.Clt: return new BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2); #endregion #region Logical case ILCode.LogicNot: return new UnaryOperatorExpression(UnaryOperatorType.Not, arg1); case ILCode.LogicAnd: return new BinaryOperatorExpression(arg1, BinaryOperatorType.ConditionalAnd, arg2); case ILCode.LogicOr: return new BinaryOperatorExpression(arg1, BinaryOperatorType.ConditionalOr, arg2); case ILCode.TernaryOp: return new ConditionalExpression() { Condition = arg1, TrueExpression = arg2, FalseExpression = arg3 }; case ILCode.NullCoalescing: return new BinaryOperatorExpression(arg1, BinaryOperatorType.NullCoalescing, arg2); #endregion #region Branch case ILCode.Br: return new GotoStatement(((ILLabel)byteCode.Operand).Name); case ILCode.Brtrue: return new IfElseStatement() { Condition = arg1, TrueStatement = new BlockStatement() { new GotoStatement(((ILLabel)byteCode.Operand).Name) } }; case ILCode.LoopOrSwitchBreak: return new BreakStatement(); case ILCode.LoopContinue: return new ContinueStatement(); #endregion #region Conversions case ILCode.Conv_I1: case ILCode.Conv_I2: case ILCode.Conv_I4: case ILCode.Conv_I8: case ILCode.Conv_U1: case ILCode.Conv_U2: case ILCode.Conv_U4: case ILCode.Conv_U8: case ILCode.Conv_I: case ILCode.Conv_U: { // conversion was handled by Convert() function using the info from type analysis CastExpression cast = arg1 as CastExpression; if (cast != null) { cast.AddAnnotation(AddCheckedBlocks.UncheckedAnnotation); } return arg1; } case ILCode.Conv_R4: case ILCode.Conv_R8: case ILCode.Conv_R_Un: // TODO return arg1; case ILCode.Conv_Ovf_I1: case ILCode.Conv_Ovf_I2: case ILCode.Conv_Ovf_I4: case ILCode.Conv_Ovf_I8: case ILCode.Conv_Ovf_U1: case ILCode.Conv_Ovf_U2: case ILCode.Conv_Ovf_U4: case ILCode.Conv_Ovf_U8: case ILCode.Conv_Ovf_I1_Un: case ILCode.Conv_Ovf_I2_Un: case ILCode.Conv_Ovf_I4_Un: case ILCode.Conv_Ovf_I8_Un: case ILCode.Conv_Ovf_U1_Un: case ILCode.Conv_Ovf_U2_Un: case ILCode.Conv_Ovf_U4_Un: case ILCode.Conv_Ovf_U8_Un: case ILCode.Conv_Ovf_I: case ILCode.Conv_Ovf_U: case ILCode.Conv_Ovf_I_Un: case ILCode.Conv_Ovf_U_Un: { // conversion was handled by Convert() function using the info from type analysis CastExpression cast = arg1 as CastExpression; if (cast != null) { cast.AddAnnotation(AddCheckedBlocks.CheckedAnnotation); } return arg1; } case ILCode.Unbox_Any: // unboxing does not require a cast if the argument was an isinst instruction if (arg1 is AsExpression && byteCode.Arguments[0].Code == ILCode.Isinst && TypeAnalysis.IsSameType(operand as ITypeDefOrRef, byteCode.Arguments[0].Operand as ITypeDefOrRef)) return arg1; else goto case ILCode.Castclass; case ILCode.Castclass: if ((byteCode.Arguments[0].InferredType != null && byteCode.Arguments[0].InferredType.IsGenericParameter) || ((ITypeDefOrRef)operand).TryGetGenericSig() != null) return arg1.CastTo(new PrimitiveType("object").WithAnnotation(context.CurrentModule.CorLibTypes.Object.ToTypeDefOrRef())).CastTo(operandAsTypeRef); else return arg1.CastTo(operandAsTypeRef); case ILCode.Isinst: return arg1.CastAs(operandAsTypeRef); case ILCode.Box: return arg1; case ILCode.Unbox: return MakeRef(arg1.CastTo(operandAsTypeRef)); #endregion #region Indirect case ILCode.Ldind_Ref: case ILCode.Ldobj: if (arg1 is DirectionExpression) return ((DirectionExpression)arg1).Expression.Detach(); else return new UnaryOperatorExpression(UnaryOperatorType.Dereference, arg1); case ILCode.Stind_Ref: case ILCode.Stobj: if (arg1 is DirectionExpression) return new AssignmentExpression(((DirectionExpression)arg1).Expression.Detach(), arg2); else return new AssignmentExpression(new UnaryOperatorExpression(UnaryOperatorType.Dereference, arg1), arg2); #endregion case ILCode.Arglist: return new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.ArgListAccess }; case ILCode.Break: return InlineAssembly(byteCode, args); case ILCode.Call: case ILCode.CallGetter: case ILCode.CallSetter: return TransformCall(false, byteCode, args); case ILCode.Callvirt: case ILCode.CallvirtGetter: case ILCode.CallvirtSetter: return TransformCall(true, byteCode, args); case ILCode.Ldftn: { IMethod method = (IMethod)operand; var expr = new IdentifierExpression(method.Name); expr.TypeArguments.AddRange(ConvertTypeArguments(method)); expr.AddAnnotation(method); return new IdentifierExpression("ldftn").Invoke(expr) .WithAnnotation(new DelegateConstruction.Annotation(false)); } case ILCode.Ldvirtftn: { IMethod method = (IMethod)operand; var expr = new IdentifierExpression(method.Name); expr.TypeArguments.AddRange(ConvertTypeArguments(method)); expr.AddAnnotation(method); return new IdentifierExpression("ldvirtftn").Invoke(expr) .WithAnnotation(new DelegateConstruction.Annotation(true)); } case ILCode.Calli: return InlineAssembly(byteCode, args); case ILCode.Ckfinite: return InlineAssembly(byteCode, args); case ILCode.Constrained: return InlineAssembly(byteCode, args); case ILCode.Cpblk: return InlineAssembly(byteCode, args); case ILCode.Cpobj: return InlineAssembly(byteCode, args); case ILCode.Dup: return arg1; case ILCode.Endfilter: return new ReturnStatement { Expression = arg1 }; case ILCode.Endfinally: return null; case ILCode.Initblk: return InlineAssembly(byteCode, args); case ILCode.Initobj: return InlineAssembly(byteCode, args); case ILCode.DefaultValue: return MakeDefaultValue(((ITypeDefOrRef)operand).ToTypeSig()); case ILCode.Jmp: return InlineAssembly(byteCode, args); case ILCode.Ldc_I4: return AstBuilder.MakePrimitive((int)operand, byteCode.InferredType); case ILCode.Ldc_I8: return AstBuilder.MakePrimitive((long)operand, byteCode.InferredType); case ILCode.Ldc_R4: case ILCode.Ldc_R8: case ILCode.Ldc_Decimal: return new PrimitiveExpression(operand); case ILCode.Ldfld: if (arg1 is DirectionExpression) arg1 = ((DirectionExpression)arg1).Expression.Detach(); return arg1.Member(((IField)operand).Name).WithAnnotation(operand); case ILCode.Ldsfld: return AstBuilder.ConvertType(((IField)operand).DeclaringType) .Member(((IField)operand).Name).WithAnnotation(operand); case ILCode.Stfld: if (arg1 is DirectionExpression) arg1 = ((DirectionExpression)arg1).Expression.Detach(); return new AssignmentExpression(arg1.Member(((IField)operand).Name).WithAnnotation(operand), arg2); case ILCode.Stsfld: return new AssignmentExpression( AstBuilder.ConvertType(((IField)operand).DeclaringType) .Member(((IField)operand).Name).WithAnnotation(operand), arg1); case ILCode.Ldflda: if (arg1 is DirectionExpression) arg1 = ((DirectionExpression)arg1).Expression.Detach(); return MakeRef(arg1.Member(((IField)operand).Name).WithAnnotation(operand)); case ILCode.Ldsflda: return MakeRef( AstBuilder.ConvertType(((IField)operand).DeclaringType) .Member(((IField)operand).Name).WithAnnotation(operand)); case ILCode.Ldloc: { ILVariable v = (ILVariable)operand; if (!v.IsParameter) localVariablesToDefine.Add((ILVariable)operand); Expression expr; if (v.IsParameter && v.OriginalParameter.IsHiddenThisParameter) expr = new ThisReferenceExpression(); else expr = new IdentifierExpression(((ILVariable)operand).Name).WithAnnotation(operand); return v.IsParameter && v.Type is ByRefSig ? MakeRef(expr) : expr; } case ILCode.Ldloca: { ILVariable v = (ILVariable)operand; if (v.IsParameter && v.OriginalParameter.IsHiddenThisParameter) return MakeRef(new ThisReferenceExpression()); if (!v.IsParameter) localVariablesToDefine.Add((ILVariable)operand); return MakeRef(new IdentifierExpression(((ILVariable)operand).Name).WithAnnotation(operand)); } case ILCode.Ldnull: return new NullReferenceExpression(); case ILCode.Ldstr: return new PrimitiveExpression(operand); case ILCode.Ldtoken: if (operand is ITypeDefOrRef) { return AstBuilder.CreateTypeOfExpression(((ITypeDefOrRef)operand).ToTypeSig()).Member("TypeHandle").WithAnnotation(GetTypeHandleRef()); } else { Expression referencedEntity; string loadName; string handleName; MemberRef memberRef; if (dnlibExtensions.IsField(operand)) { loadName = "fieldof"; handleName = "FieldHandle"; memberRef = GetFieldHandleRef(); IField fr = (IField)operand; referencedEntity = AstBuilder.ConvertType(fr.DeclaringType).Member(fr.Name).WithAnnotation(fr); } else if (dnlibExtensions.IsMethod(operand)) { loadName = "methodof"; handleName = "MethodHandle"; memberRef = GetMethodHandleRef(); IMethod mr = (IMethod)operand; var methodParameters = mr.MethodSig.Params.Select(p => new TypeReferenceExpression(AstBuilder.ConvertType(p))); referencedEntity = AstBuilder.ConvertType(mr.DeclaringType).Invoke(mr.Name, methodParameters).WithAnnotation(mr); } else { loadName = "ldtoken"; handleName = "Handle"; memberRef = null; referencedEntity = new IdentifierExpression(FormatByteCodeOperand(byteCode.Operand)); } return new IdentifierExpression(loadName).Invoke(referencedEntity).WithAnnotation(new LdTokenAnnotation()).Member(handleName); } case ILCode.Leave: return new GotoStatement() { Label = ((ILLabel)operand).Name }; case ILCode.Localloc: { PtrSig ptrType = byteCode.InferredType as PtrSig; TypeSig type; if (ptrType != null) { type = ptrType.Next; } else { type = typeSystem.Byte; } return new StackAllocExpression { Type = AstBuilder.ConvertType(type), CountExpression = arg1 }; } case ILCode.Mkrefany: { DirectionExpression dir = arg1 as DirectionExpression; if (dir != null) { return new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.MakeRef, Arguments = { dir.Expression.Detach() } }; } else { return InlineAssembly(byteCode, args); } } case ILCode.Refanytype: return new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.RefType, Arguments = { arg1 } }.Member("TypeHandle").WithAnnotation(GetTypeHandleRef()); case ILCode.Refanyval: return MakeRef( new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.RefValue, Arguments = { arg1, new TypeReferenceExpression(operandAsTypeRef) } }); case ILCode.Newobj: { ITypeDefOrRef declaringType = ((IMethod)operand).DeclaringType; if (declaringType.TryGetArraySig() != null) { ComposedType ct = AstBuilder.ConvertType(declaringType) as ComposedType; if (ct != null && ct.ArraySpecifiers.Count >= 1) { var ace = new ArrayCreateExpression(); ct.ArraySpecifiers.First().Remove(); ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers); ace.Type = ct; ace.Arguments.AddRange(args); return ace; } } if (declaringType.IsAnonymousType()) { MethodDef ctor = ((IMethod)operand).ResolveMethodDef(); if (ctor != null) { AnonymousTypeCreateExpression atce = new AnonymousTypeCreateExpression(); if (CanInferAnonymousTypePropertyNamesFromArguments(args, ctor.Parameters)) { atce.Initializers.AddRange(args); } else { for (int i = 0; i < args.Count; i++) { atce.Initializers.Add( new NamedExpression { Name = ctor.Parameters[i].Name, Expression = args[i] }); } } return atce; } } var oce = new ObjectCreateExpression(); oce.Type = AstBuilder.ConvertType(declaringType); oce.Arguments.AddRange(args); return oce.WithAnnotation(operand); } case ILCode.Nop: return null; case ILCode.Pop: return arg1; case ILCode.Readonly: return InlineAssembly(byteCode, args); case ILCode.Ret: if (methodDef.ReturnType.FullName != "System.Void") { return new ReturnStatement { Expression = arg1 }; } else { return new ReturnStatement(); } case ILCode.Rethrow: return new ThrowStatement(); case ILCode.Sizeof: return new SizeOfExpression { Type = operandAsTypeRef }; case ILCode.Stloc: { ILVariable locVar = (ILVariable)operand; if (!locVar.IsParameter) localVariablesToDefine.Add(locVar); return new AssignmentExpression(new IdentifierExpression(locVar.Name).WithAnnotation(locVar), arg1); } case ILCode.Switch: return InlineAssembly(byteCode, args); case ILCode.Tail: return InlineAssembly(byteCode, args); case ILCode.Throw: return new ThrowStatement { Expression = arg1 }; case ILCode.Unaligned: return InlineAssembly(byteCode, args); case ILCode.Volatile: return InlineAssembly(byteCode, args); case ILCode.YieldBreak: return new YieldBreakStatement(); case ILCode.YieldReturn: return new YieldReturnStatement { Expression = arg1 }; case ILCode.InitObject: case ILCode.InitCollection: { ArrayInitializerExpression initializer = new ArrayInitializerExpression(); for (int i = 1; i < args.Count; i++) { Match m = objectInitializerPattern.Match(args[i]); if (m.Success) { MemberReferenceExpression mre = m.Get<MemberReferenceExpression>("left").Single(); var exp = new NamedExpression { Name = mre.MemberName, Expression = m.Get<Expression>("right").Single().Detach() }; exp.NameToken.CopyAnnotationsFrom(mre); initializer.Elements.Add(exp); } else { m = collectionInitializerPattern.Match(args[i]); if (m.Success) { if (m.Get("arg").Count() == 1) { initializer.Elements.Add(m.Get<Expression>("arg").Single().Detach()); } else { ArrayInitializerExpression argList = new ArrayInitializerExpression(); foreach (var expr in m.Get<Expression>("arg")) { argList.Elements.Add(expr.Detach()); } initializer.Elements.Add(argList); } } else { initializer.Elements.Add(args[i]); } } } ObjectCreateExpression oce = arg1 as ObjectCreateExpression; DefaultValueExpression dve = arg1 as DefaultValueExpression; if (oce != null) { oce.Initializer = initializer; return oce; } else if (dve != null) { oce = new ObjectCreateExpression(dve.Type.Detach()); oce.CopyAnnotationsFrom(dve); oce.Initializer = initializer; return oce; } else { return new AssignmentExpression(arg1, initializer); } } case ILCode.InitializedObject: return new InitializedObjectExpression(); case ILCode.Wrap: return arg1.WithAnnotation(PushNegation.LiftedOperatorAnnotation); case ILCode.AddressOf: return MakeRef(arg1); case ILCode.ExpressionTreeParameterDeclarations: args[args.Count - 1].AddAnnotation(new ParameterDeclarationAnnotation(byteCode)); return args[args.Count - 1]; case ILCode.Await: return new UnaryOperatorExpression(UnaryOperatorType.Await, UnpackDirectionExpression(arg1)); case ILCode.NullableOf: case ILCode.ValueOf: return arg1; default: throw new Exception("Unknown OpCode: " + byteCode.Code); } }
public virtual void VisitNamedExpression(NamedExpression namedExpression) { DebugExpression(namedExpression); StartNode(namedExpression); WriteIdentifier(namedExpression.NameToken); Space(); WriteToken(Roles.Assign, BoxedTextColor.Operator); Space(); namedExpression.Expression.AcceptVisitor(this); EndNode(namedExpression); }
public override bool Walk(NamedExpression node) { AssignmentHandler.HandleNamedExpression(node); return(base.Walk(node)); }
public override void VisitNamedExpression(NamedExpression namedExpression) { VisitBinaryExpression(namedExpression); }
public override bool Walk(NamedExpression node) { node.Value?.Walk(this); return(false); }
public override bool Walk(NamedExpression node) { node.Value?.Walk(this); AddVarSymbolRecursive(node.Target); return(false); }
public void VisitNamedExpression(NamedExpression namedExpression) { throw new NotImplementedException(); }
void AddConvertCollectionOrObjectInitializers(Expression init, CollectionOrObjectInitializers minit) { var initLoc = LocationsBag.GetLocations(minit); var commaLoc = LocationsBag.GetLocations(minit.Initializers); int curComma = 0; init.AddChild(new CSharpTokenNode(Convert(minit.Location), Roles.LBrace), Roles.LBrace); foreach (var expr in minit.Initializers) { var collectionInit = expr as CollectionElementInitializer; if (collectionInit != null) { AstNode parent; // For ease of use purposes in the resolver the ast representation // of { a, b, c } is { {a}, {b}, {c} } - but the generated ArrayInitializerExpression // can be identified by expr.IsSingleElement. if (!collectionInit.IsSingle) { parent = new ArrayInitializerExpression(); parent.AddChild(new CSharpTokenNode(Convert(collectionInit.Location), Roles.LBrace), Roles.LBrace); } else { parent = ArrayInitializerExpression.CreateSingleElementInitializer(); } if (collectionInit.Arguments != null) { for (int i = 0; i < collectionInit.Arguments.Count; i++) { var arg = collectionInit.Arguments [i] as CollectionElementInitializer.ElementInitializerArgument; if (arg == null || arg.Expr == null) continue; parent.AddChild( (Expression)arg.Expr.Accept(this), Roles.Expression ); } } if (!collectionInit.IsSingle) { var braceLocs = LocationsBag.GetLocations(expr); if (braceLocs != null) parent.AddChild(new CSharpTokenNode(Convert(braceLocs [0]), Roles.RBrace), Roles.RBrace); } init.AddChild((ArrayInitializerExpression)parent, Roles.Expression); } else { var eleInit = expr as ElementInitializer; if (eleInit != null) { var nexpr = new NamedExpression(); nexpr.AddChild( Identifier.Create(eleInit.Name, Convert(eleInit.Location)), Roles.Identifier ); var assignLoc = LocationsBag.GetLocations(eleInit); if (assignLoc != null) nexpr.AddChild(new CSharpTokenNode(Convert(assignLoc [0]), Roles.Assign), Roles.Assign); if (eleInit.Source != null) { var colInit = eleInit.Source as CollectionOrObjectInitializers; if (colInit != null) { var arrInit = new ArrayInitializerExpression(); AddConvertCollectionOrObjectInitializers( arrInit, colInit ); nexpr.AddChild(arrInit, Roles.Expression); } else { nexpr.AddChild((Expression)eleInit.Source.Accept(this), Roles.Expression); } } init.AddChild(nexpr, Roles.Expression); } } if (commaLoc != null && curComma < commaLoc.Count) init.AddChild(new CSharpTokenNode(Convert(commaLoc [curComma++]), Roles.Comma), Roles.Comma); } if (initLoc != null) { if (initLoc.Count == 2) // optional comma init.AddChild(new CSharpTokenNode(Convert(initLoc [0]), Roles.Comma), Roles.Comma); init.AddChild(new CSharpTokenNode(Convert(initLoc [initLoc.Count - 1]), Roles.RBrace), Roles.RBrace); } }
protected virtual void WriteObjectInitializer(IEnumerable <Expression> expressions, TypeDefinition type, InvocationResolveResult rr, bool withCtor) { bool needComma = false; List <string> names = new List <string>(); var isObjectLiteral = this.Emitter.Validator.IsObjectLiteral(type); if (!withCtor && rr != null && this.ObjectCreateExpression.Arguments.Count > 0) { var args = this.ObjectCreateExpression.Arguments.ToList(); var arrIsOpen = false; for (int i = 0; i < args.Count; i++) { Expression expression = args[i]; var p = rr.Member.Parameters[i < rr.Member.Parameters.Count ? i : (rr.Member.Parameters.Count - 1)]; var name = p.Name; if (p.Type.FullName == "Bridge.DefaultValueMode" || p.Type.FullName == "Bridge.ObjectInitializationMode" || p.Type.FullName == "Bridge.ObjectCreateMode") { continue; } if (needComma) { this.WriteComma(); } needComma = true; if (p.IsParams && !arrIsOpen) { arrIsOpen = true; this.Write("["); } this.Write(name, ": "); expression.AcceptVisitor(this.Emitter); names.Add(name); } if (arrIsOpen) { this.Write("]"); } } if (expressions != null) { foreach (Expression item in expressions) { NamedExpression namedExression = item as NamedExpression; NamedArgumentExpression namedArgumentExpression = item as NamedArgumentExpression; string name = namedExression != null ? namedExression.Name : namedArgumentExpression.Name; var itemrr = this.Emitter.Resolver.ResolveNode(item, this.Emitter) as MemberResolveResult; if (itemrr != null) { var oc = OverloadsCollection.Create(this.Emitter, itemrr.Member); name = oc.GetOverloadName(); if (!this.Emitter.AssemblyInfo.PreserveMemberCase && itemrr.Member is IProperty && !itemrr.Member.Attributes.Any(attr => attr.AttributeType.FullName == "Bridge.NameAttribute") && !this.Emitter.Validator.IsObjectLiteral(itemrr.Member.DeclaringTypeDefinition)) { name = Object.Net.Utilities.StringUtils.ToLowerCamelCase(name); } } if (needComma) { this.WriteComma(); } needComma = true; Expression expression = namedExression != null ? namedExression.Expression : namedArgumentExpression.Expression; this.Write(name, ": "); expression.AcceptVisitor(this.Emitter); names.Add(name); } } if (isObjectLiteral) { var key = BridgeTypes.GetTypeDefinitionKey(type); var tinfo = this.Emitter.Types.FirstOrDefault(t => t.Key == key); if (tinfo == null) { return; } var itype = tinfo.Type as ITypeDefinition; var mode = 0; if (rr != null) { if (rr.Member.Parameters.Count > 0) { var prm = rr.Member.Parameters.FirstOrDefault(p => p.Type.FullName == "Bridge.ObjectInitializationMode"); if (prm != null) { var prmIndex = rr.Member.Parameters.IndexOf(prm); var arg = rr.Arguments.FirstOrDefault(a => { if (a is NamedArgumentResolveResult) { return(((NamedArgumentResolveResult)a).ParameterName == prm.Name); } return(prmIndex == rr.Arguments.IndexOf(a)); }); if (arg != null && arg.ConstantValue != null && (int)arg.ConstantValue == 1) { mode = (int)arg.ConstantValue; } } } else if (itype != null) { mode = this.Emitter.Validator.GetObjectInitializationMode(type); } } if (mode != 0) { var members = tinfo.InstanceConfig.Fields.Concat(tinfo.InstanceConfig.Properties); if (members.Any()) { foreach (var member in members) { if (mode == 1 && (member.VarInitializer == null || member.VarInitializer.Initializer.IsNull)) { continue; } var name = member.GetName(this.Emitter); if (names.Contains(name)) { continue; } if (needComma) { this.WriteComma(); } needComma = true; this.Write(name, ": "); var primitiveExpr = member.Initializer as PrimitiveExpression; if (primitiveExpr != null && primitiveExpr.Value is AstType) { this.Write(Inspector.GetStructDefaultValue((AstType)primitiveExpr.Value, this.Emitter)); } else { member.Initializer.AcceptVisitor(this.Emitter); } } } } } }
public void VisitNamedExpression(NamedExpression node) { NotSupported(node); }
/// <summary> /// Initializes a new instance of the Expression class using multiple parameters. /// </summary> /// <param name="parentTabularModel">TabularModel object that the Expression object belongs to.</param> /// <param name="expression">Tabular Object Model Expression object abtstracted by the Expression class.</param> public Expression(TabularModel parentTabularModel, NamedExpression expression) : base(expression, parentTabularModel.Model.Name) { _parentTabularModel = parentTabularModel; _tomExpression = expression; }
public Expression ProcessNames(NamedExpression outerExpression) { ArgumentUtility.CheckNotNull("outerExpression", outerExpression); // We cannot implement this as an expression visitor because expression visitors have no fallback case, i.e., there is no good possibility // to catch all cases not explicitly handled by a visitor. We need that catch-all case, however, and don't want to automatically visit the // expressions' children. if (outerExpression.Expression is NewExpression) { var newExpression = (NewExpression)outerExpression.Expression; var preparedArguments = newExpression.Arguments.Select(expr => ProcessNames(new NamedExpression(outerExpression.Name, expr))); if (newExpression.Members != null && newExpression.Members.Count > 0) { return(Expression.New(newExpression.Constructor, preparedArguments, newExpression.Members)); } else { return(Expression.New(newExpression.Constructor, preparedArguments)); } } else if (outerExpression.Expression is MethodCallExpression) { var methodCallExpression = (MethodCallExpression)outerExpression.Expression; var namedInstance = methodCallExpression.Object != null ? new NamedExpression(outerExpression.Name, methodCallExpression.Object) : null; var namedArguments = methodCallExpression.Arguments.Select((a, i) => new NamedExpression(outerExpression.Name, a)); return(Expression.Call( namedInstance != null ? ProcessNames(namedInstance) : null, methodCallExpression.Method, namedArguments.Select(ProcessNames))); } else if (outerExpression.Expression is SqlEntityExpression) { var entityExpression = (SqlEntityExpression)outerExpression.Expression; string newName = CombineNames(outerExpression.Name, entityExpression.Name); return(_mappingResolutionContext.UpdateEntityAndAddMapping(entityExpression, entityExpression.Type, entityExpression.TableAlias, newName)); } else if (outerExpression.Expression is NamedExpression) { var namedExpression = (NamedExpression)outerExpression.Expression; var newName = CombineNames(outerExpression.Name, namedExpression.Name); return(ProcessNames(new NamedExpression(newName, namedExpression.Expression))); } else if (outerExpression.Expression is SqlGroupingSelectExpression) { var groupingSelectExpression = (SqlGroupingSelectExpression)outerExpression.Expression; var newKeyExpression = ProcessNames(new NamedExpression(outerExpression.Name, groupingSelectExpression.KeyExpression)); var newElementExpression = ProcessNames(new NamedExpression(outerExpression.Name, groupingSelectExpression.ElementExpression)); var newAggregationExpressions = groupingSelectExpression.AggregationExpressions.Select(e => ProcessNames(new NamedExpression(outerExpression.Name, e))); return(_mappingResolutionContext.UpdateGroupingSelectAndAddMapping( groupingSelectExpression, newKeyExpression, newElementExpression, newAggregationExpressions)); } else if (outerExpression.Expression.NodeType == ExpressionType.Convert || outerExpression.Expression.NodeType == ExpressionType.ConvertChecked) { var unaryExpression = (UnaryExpression)outerExpression.Expression; var innerNamedExpression = new NamedExpression(outerExpression.Name, unaryExpression.Operand); return(Expression.MakeUnary( unaryExpression.NodeType, ProcessNames(innerNamedExpression), unaryExpression.Type, unaryExpression.Method)); } else { return(outerExpression); } }
public StringBuilder VisitNamedExpression(NamedExpression namedExpression) { throw new NotImplementedException(); }
public override void VisitNamedExpression(NamedExpression namedExpression) { new NameBlock(this, namedExpression).Emit(); }
public override AstNode VisitNamedExpression(NamedExpression namedExpression, ILGenerator data) { return(_constructorEmitter.EmitNamedExpression(namedExpression, data)); }
public override void VisitNamedExpression(NamedExpression namedExpression) { namedExpression.Expression.AcceptVisitor(this); }
public override void VisitNamedExpression (NamedExpression namedExpression) { if (InsertParenthesesForReadability) { ParenthesizeIfRequired(namedExpression.Expression, RelationalAndTypeTesting + 1); } base.VisitNamedExpression (namedExpression); }
public override void VisitNamedExpression(NamedExpression namedExpression) { ForceSpacesAround(namedExpression.AssignToken, policy.SpaceAroundAssignment); base.VisitNamedExpression(namedExpression); }
IEnumerable<Attribute> GetAttributes (List<Mono.CSharp.Attribute> optAttributes) { if (optAttributes == null) yield break; foreach (var attr in optAttributes) { Attribute result = new Attribute (); result.Type = ConvertToType (attr.TypeNameExpression); var loc = LocationsBag.GetLocations (attr); result.HasArgumentList = loc != null; if (loc != null) result.AddChild (new CSharpTokenNode (Convert (loc [0]), 1), AttributeSection.Roles.LPar); if (attr.PosArguments != null) { foreach (var arg in attr.PosArguments) { result.AddChild ((Expression)arg.Expr.Accept (this), Attribute.Roles.Argument); } } if (attr.NamedArguments != null) { foreach (NamedArgument na in attr.NamedArguments) { var newArg = new NamedExpression (); newArg.AddChild (Identifier.Create (na.Name, Convert (na.Location)), NamedExpression.Roles.Identifier); var argLoc = LocationsBag.GetLocations (na); if (argLoc != null) newArg.AddChild (new CSharpTokenNode (Convert (argLoc[0]), 1), NamedExpression.Roles.Assign); newArg.AddChild ((Expression)na.Expr.Accept (this), NamedExpression.Roles.Expression); result.AddChild (newArg, Attribute.Roles.Argument); } } if (loc != null) result.AddChild (new CSharpTokenNode (Convert (loc [1]), 1), AttributeSection.Roles.RPar); yield return result; } }
public void SetUp() { _wrappedExpression = Expression.Constant(1); _namedExpression = new NamedExpression("test", _wrappedExpression); }
protected virtual void WriteObjectInitializer(IEnumerable <Expression> expressions, bool changeCase, bool valuesOnly = false) { bool needComma = false; foreach (Expression item in expressions) { NamedExpression namedExression = null; NamedArgumentExpression namedArgumentExpression = null; IdentifierExpression identifierExpression = null; MemberReferenceExpression memberReferenceExpression = null; namedExression = item as NamedExpression; if (namedExression == null) { namedArgumentExpression = item as NamedArgumentExpression; if (namedArgumentExpression == null) { identifierExpression = item as IdentifierExpression; if (identifierExpression == null) { memberReferenceExpression = item as MemberReferenceExpression; } } } if (needComma) { this.WriteComma(); } needComma = true; string name; Expression expression; if (namedExression != null) { name = namedExression.Name; expression = namedExression.Expression; } else if (namedArgumentExpression != null) { name = namedArgumentExpression.Name; expression = namedArgumentExpression.Expression; } else if (identifierExpression != null) { name = identifierExpression.Identifier; expression = identifierExpression; } else { name = memberReferenceExpression.MemberName; expression = memberReferenceExpression; } if (changeCase) { name = Object.Net.Utilities.StringUtils.ToLowerCamelCase(name); } if (!valuesOnly) { this.Write(name, ": "); } expression.AcceptVisitor(this.Emitter); } }
public override void VisitNamedExpression(NamedExpression namedExpression) { throw NotSupportedToConsistency(); }
public override void VisitNamedExpression(NamedExpression syntax) { _underlyingVisitor.VisitNamedExpression(syntax); }
public void VisitQuerySourceReferenceExpression_WithOrderings_AndExtractOrdingsPolicy() { var sqlTable = SqlStatementModelObjectMother.CreateSqlTable(typeof(Cook)); var sqlTableReferenceExpression = new SqlTableReferenceExpression(sqlTable); var selectProjection = new NamedExpression("test", Expression.MakeMemberAccess(sqlTableReferenceExpression, typeof(Cook).GetProperty("Name"))); var orderingExpression = Expression.MakeMemberAccess(sqlTableReferenceExpression, typeof(Cook).GetProperty("ID")); var sqlStatement = new SqlStatementBuilder { DataInfo = new StreamedSequenceInfo(typeof(DateTime[]), Expression.Constant(new DateTime(2000, 1, 1))), SelectProjection = selectProjection, SqlTables = { sqlTable }, Orderings = { new Ordering(orderingExpression, OrderingDirection.Asc) } }.GetSqlStatement(); var fakeSelectExpression = Expression.Constant(new KeyValuePair <string, int>("test", 5)); var fakeWhereExpression = Expression.Constant(true); var innerSequenceExpression = new SqlSubStatementExpression(sqlStatement); var joinClause = new JoinClause( "x", typeof(Cook[]), innerSequenceExpression, Expression.Constant(new Cook()), Expression.Constant(new Cook())); var groupJoinClause = new GroupJoinClause("g", typeof(Cook[]), joinClause); var querySourceReferenceExpression = new QuerySourceReferenceExpression(groupJoinClause); _stageMock .Expect(mock => mock.PrepareSelectExpression(Arg <Expression> .Is.Anything, Arg <ISqlPreparationContext> .Is.Anything)) .Return(fakeSelectExpression); _stageMock .Expect(mock => mock.PrepareWhereExpression(Arg <Expression> .Matches(e => e is BinaryExpression), Arg.Is(_context))) .WhenCalled( mi => SqlExpressionTreeComparer.CheckAreEqualTrees( Expression.Equal(groupJoinClause.JoinClause.OuterKeySelector, groupJoinClause.JoinClause.InnerKeySelector), (Expression)mi.Arguments[0])) .Return(fakeWhereExpression); _stageMock.Replay(); var visitor = CreateTestableVisitor(OrderingExtractionPolicy.ExtractOrderingsIntoProjection); visitor.VisitQuerySourceReference(querySourceReferenceExpression); _stageMock.VerifyAllExpectations(); Assert.That(visitor.FromExpressionInfo != null); // inline condition because of ReSharper var fromExpressionInfo = (FromExpressionInfo)visitor.FromExpressionInfo; Assert.That(fromExpressionInfo.ExtractedOrderings.Count, Is.EqualTo(1)); Assert.That(fromExpressionInfo.ExtractedOrderings[0].Expression, Is.AssignableTo(typeof(MemberExpression))); Assert.That(((MemberExpression)fromExpressionInfo.ExtractedOrderings[0].Expression).Expression, Is.TypeOf(typeof(SqlTableReferenceExpression))); Assert.That( ((SqlTableReferenceExpression)((MemberExpression)fromExpressionInfo.ExtractedOrderings[0].Expression).Expression).SqlTable, Is.TypeOf(typeof(SqlTable))); Assert.That( ((SqlTable)((SqlTableReferenceExpression)((MemberExpression)fromExpressionInfo.ExtractedOrderings[0].Expression).Expression).SqlTable).TableInfo, Is.TypeOf(typeof(ResolvedSubStatementTableInfo))); var resolvedSubStatementtableInfo = (ResolvedSubStatementTableInfo)((SqlTable)((SqlTableReferenceExpression)((MemberExpression)fromExpressionInfo.ExtractedOrderings[0].Expression).Expression).SqlTable).TableInfo; Assert.That(resolvedSubStatementtableInfo.SqlStatement.SelectProjection, Is.SameAs(fakeSelectExpression)); Assert.That(resolvedSubStatementtableInfo.SqlStatement.Orderings.Count, Is.EqualTo(0)); Assert.That(((MemberExpression)fromExpressionInfo.ExtractedOrderings[0].Expression).Member, Is.EqualTo(typeof(KeyValuePair <,>).MakeGenericType(typeof(string), typeof(int)).GetProperty("Value"))); Assert.That(fromExpressionInfo.ItemSelector, Is.AssignableTo(typeof(MemberExpression))); Assert.That(((MemberExpression)fromExpressionInfo.ItemSelector).Expression, Is.TypeOf(typeof(SqlTableReferenceExpression))); Assert.That(((SqlTableReferenceExpression)((MemberExpression)fromExpressionInfo.ItemSelector).Expression).SqlTable, Is.TypeOf(typeof(SqlTable))); Assert.That( ((SqlTable)((SqlTableReferenceExpression)((MemberExpression)fromExpressionInfo.ItemSelector).Expression).SqlTable).TableInfo, Is.TypeOf(typeof(ResolvedSubStatementTableInfo))); Assert.That(((MemberExpression)fromExpressionInfo.ItemSelector).Member, Is.EqualTo(typeof(KeyValuePair <,>).MakeGenericType(typeof(string), typeof(int)).GetProperty("Key"))); }
bool InsertImplicitInitializersForPath(AccessPath path) { if (accessPaths.ContainsKey(path)) return true; if (path.MemberPath.Count == 0) return false; var parentPath = path.GetParentPath(); var success = InsertImplicitInitializersForPath(parentPath); if (!success) return false; var parentInitializer = accessPaths [parentPath]; var initializer = new ArrayInitializerExpression(); var namedExpression = new NamedExpression(path.MemberPath [path.MemberPath.Count - 1].Name, initializer); AddToInitializer(parentInitializer, namedExpression); accessPaths [path] = initializer; return true; }
public virtual void VisitNamedExpression(NamedExpression namedExpression) { VisitChildren(namedExpression); }
public override object Visit (NewAnonymousType newAnonymousType) { var result = new AnonymousTypeCreateExpression (); if (newAnonymousType.Parameters == null) return result; foreach (var par in newAnonymousType.Parameters) { var location = LocationsBag.GetLocations (par); if (location == null) { if (par.Expr != null) result.AddChild ((Expression)par.Expr.Accept (this), AnonymousTypeCreateExpression.Roles.Expression); } else { var namedExpression = new NamedExpression (); namedExpression.AddChild (Identifier.Create (par.Name, Convert (par.Location)), AnonymousTypeCreateExpression.Roles.Identifier); namedExpression.AddChild (new CSharpTokenNode (Convert (location[0]), 1), AnonymousTypeCreateExpression.Roles.Assign); if (par.Expr != null) namedExpression.AddChild ((Expression)par.Expr.Accept (this), AnonymousTypeCreateExpression.Roles.Expression); result.AddChild (namedExpression, AnonymousTypeCreateExpression.Roles.Expression); } } return result; }
/// <inheritdoc/> public virtual void VisitNamedExpression(NamedExpression syntax) { VisitNode(syntax); }
public override object Visit(NewAnonymousType newAnonymousType) { var result = new AnonymousTypeCreateExpression(); var location = LocationsBag.GetLocations(newAnonymousType); result.AddChild(new CSharpTokenNode(Convert(newAnonymousType.Location), ObjectCreateExpression.NewKeywordRole), ObjectCreateExpression.NewKeywordRole); if (location != null) result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LBrace), Roles.LBrace); if (newAnonymousType.Parameters != null) { foreach (var par in newAnonymousType.Parameters) { if (par == null) continue; var parLocation = LocationsBag.GetLocations(par); if (parLocation == null) { if (par.Expr != null) result.AddChild((Expression)par.Expr.Accept(this), Roles.Expression); } else { var namedExpression = new NamedExpression(); namedExpression.AddChild(Identifier.Create(par.Name, Convert(par.Location)), Roles.Identifier); namedExpression.AddChild(new CSharpTokenNode(Convert(parLocation [0]), Roles.Assign), Roles.Assign); if (par.Expr != null) namedExpression.AddChild((Expression)par.Expr.Accept(this), Roles.Expression); result.AddChild(namedExpression, Roles.Expression); } } } if (location != null && location.Count > 1) result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RBrace), Roles.RBrace); return result; }
public override void VisitNamedExpression(NamedExpression namedExpression) { HandleExpressionNode(namedExpression); }
IEnumerable<Attribute> GetAttributes(IEnumerable<Mono.CSharp.Attribute> optAttributes) { if (optAttributes == null) yield break; foreach (var attr in optAttributes) { var result = new Attribute(); result.Type = ConvertToType(attr.TypeNameExpression); var loc = LocationsBag.GetLocations(attr); result.HasArgumentList = loc != null; int pos = 0; if (loc != null) result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.LPar), Roles.LPar); if (attr.PositionalArguments != null) { foreach (var arg in attr.PositionalArguments) { if (arg == null) continue; var na = arg as NamedArgument; if (na != null) { var newArg = new NamedArgumentExpression(); newArg.AddChild(Identifier.Create(na.Name, Convert(na.Location)), Roles.Identifier); var argLoc = LocationsBag.GetLocations(na); if (argLoc != null) newArg.AddChild(new CSharpTokenNode(Convert(argLoc [0]), Roles.Colon), Roles.Colon); if (na.Expr != null) newArg.AddChild((Expression)na.Expr.Accept(this), Roles.Expression); result.AddChild(newArg, Roles.Argument); } else { if (arg.Expr != null) result.AddChild((Expression)arg.Expr.Accept(this), Roles.Argument); } if (loc != null && pos + 1 < loc.Count) result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.Comma), Roles.Comma); } } if (attr.NamedArguments != null) { foreach (var arg in attr.NamedArguments) { var na = (NamedArgument)arg; var newArg = new NamedExpression(); newArg.AddChild(Identifier.Create(na.Name, Convert(na.Location)), Roles.Identifier); var argLoc = LocationsBag.GetLocations(na); if (argLoc != null) newArg.AddChild(new CSharpTokenNode(Convert(argLoc [0]), Roles.Assign), Roles.Assign); if (na.Expr != null) newArg.AddChild((Expression)na.Expr.Accept(this), Roles.Expression); result.AddChild(newArg, Roles.Argument); if (loc != null && pos + 1 < loc.Count) result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.Comma), Roles.Comma); } } if (loc != null && pos < loc.Count) result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.RPar), Roles.RPar); yield return result; } }
public override void VisitNamedExpression(NamedExpression namedExpression) { SetState(context.Resolve(namedExpression), VariableState.Changed); base.VisitNamedExpression(namedExpression); }
public void VisitNamedExpression(NamedExpression namedExpression) { StartNode(namedExpression); namedExpression.NameToken.AcceptVisitor(this); Space(); WriteToken(Roles.Assign); Space(); namedExpression.Expression.AcceptVisitor(this); EndNode(namedExpression); }
public override void VisitVariableDeclarationStatement(VariableDeclarationStatement e) { if (e.Variables.Count == 1 && !(e.Parent is UsingStatement) && e.Variables.First().Initializer is ObjectCreateExpression) { //AssemblyName assemblyName = new AssemblyName(); //assemblyName.Name = e; //assemblyName.Version = new Version(e1); //assemblyName.CultureInfo = new CultureInfo(""); //====> //AssemblyName assemblyName = new AssemblyName() //{ // Name = e, // Version = new Version(e1), // CultureInfo = new CultureInfo("") //}; var @var = e.Variables.First(); var creation = @var.Initializer as ObjectCreateExpression; var setters = new ArrayInitializerExpression(creation.Initializer.Elements.Select(x => x.Detach())); var assignments = e.Parent.Children .SkipWhile(x => x != e) .Skip(1) .ToArray(); List<NamedExpression> processedList = new List<NamedExpression>(); foreach (var x in assignments) { var es = x as ExpressionStatement; if (es == null) break; // x.Name1 = x.Name2 = …… = value List<MemberReferenceExpression> memberRefs = new List<MemberReferenceExpression>(); Expression memberValue = null; var ae = es.Expression as AssignmentExpression; while (ae != null && ae.Operator == AssignmentOperatorType.Assign) { var left = ae.Left as MemberReferenceExpression; if (left == null) { memberRefs = null; break; } var il = left.Target as IdentifierExpression; if (il == null || il.Identifier != @var.Name) { memberRefs = null; break; } memberRefs.Add(left); memberValue = ae.Right; ae = ae.Right as AssignmentExpression; } if (memberRefs == null || memberRefs.Count == 0) break; //StoryboardTransitionBase.C_Ii1 c_Ii = new StoryboardTransitionBase.C_Ii1 //{ // f_cUb_987AB8FF = presenter, // f_7Ub_6737D612 = fromContent, // f_8Ub_6737D612 = toContent, // f_Xo_B3F66E6B = this, // f_5Ub_B15D4D71 = this.GetFromContentStoryboard(c_Ii.f_cUb_987AB8FF, c_Ii.f_7Ub_6737D612), // f_6Ub_B15D4D71 = this.GetToContentStoryboard(c_Ii.f_cUb_987AB8FF, c_Ii.f_8Ub_6737D612) //}; var query = memberValue.DescendantsAndSelf.OfType<MemberReferenceExpression>().Where(y => { IdentifierExpression ie = y.Target as IdentifierExpression; return ie != null && ie.Identifier == @var.Name; }).Select(y => new { R = y, NE = processedList.FirstOrDefault(z => z.Name == y.MemberName) }); if (query.Any(y => y.NE == null)) break; foreach (var y in query) { y.R.ReplaceWith(y.NE.Expression.Clone()); } DelayRemove(x); memberValue.Remove(); foreach (var r in memberRefs) { var element = new NamedExpression(r.MemberName, memberValue.Clone()).CopyAnnotationsFrom(r); var added = setters.Elements.FirstOrDefault(y => { NamedExpression ne = y as NamedExpression; return ne != null && ne.Name == r.MemberName; }); if (added == null) { setters.Elements.Add(element); } else { // 如果重复设置属性,后来优先 added.ReplaceWith(element); } processedList.Add(element); } } if (setters.Elements.Count > 0) { creation.Initializer = setters; } } base.VisitVariableDeclarationStatement(e); }