text:
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Syntax;

namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
    internal sealed class ExpressionTreeRewriter : ExprVisitorBase
    {
        public static Expr Rewrite(Expr expr, ExprFactory expressionFactory, SymbolLoader symbolLoader)
        {
            ExpressionTreeRewriter rewriter = new ExpressionTreeRewriter(expressionFactory, symbolLoader);
            return rewriter.Visit(expr);
        }

        private ExprFactory expressionFactory;
        private SymbolLoader symbolLoader;
        private ExprBoundLambda currentAnonMeth;

        private ExprFactory GetExprFactory() { return expressionFactory; }

        private SymbolLoader GetSymbolLoader() { return symbolLoader; }

        private ExpressionTreeRewriter(ExprFactory expressionFactory, SymbolLoader symbolLoader)
        {
            this.expressionFactory = expressionFactory;
            this.symbolLoader = symbolLoader;
        }

        protected override Expr Dispatch(Expr expr)
        {
            Debug.Assert(expr != null);

            Expr result = base.Dispatch(expr);
            if (result == expr)
            {
                throw Error.InternalCompilerError();
            }
            return result;
        }

        /////////////////////////////////////////////////////////////////////////////////
        // Statement types.
        protected override Expr VisitASSIGNMENT(ExprAssignment assignment)
        {
            Debug.Assert(assignment != null);

            // For assignments, we either have a member assignment or an indexed assignment.
            //Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL());
            Expr lhs;
            if (assignment.LHS is ExprProperty prop)
            {
                if (prop.OptionalArguments== null)
                {
                    // Regular property.
                    lhs = Visit(prop);
                }
                else
                {
                    // Indexed assignment. Here we need to find the instance of the object, create the
                    // PropInfo for the thing, and get the array of expressions that make up the index arguments.
                    //
                    // The LHS becomes Expression.Property(instance, indexerInfo, arguments).
                    Expr instance = Visit(prop.MemberGroup.OptionalObject);
                    Expr propInfo = GetExprFactory().CreatePropertyInfo(prop.PropWithTypeSlot.Prop(), prop.PropWithTypeSlot.Ats);
                    Expr arguments = GenerateParamsArray(
                        GenerateArgsList(prop.OptionalArguments),
                        PredefinedType.PT_EXPRESSION);

                    lhs = GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, instance, propInfo, arguments);
                }
            }
            else
            {
                lhs = Visit(assignment.LHS);
            }

            Expr rhs = Visit(assignment.RHS);
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs);
        }
        protected override Expr VisitMULTIGET(ExprMultiGet pExpr)
        {
            return Visit(pExpr.OptionalMulti.Left);
        }
        protected override Expr VisitMULTI(ExprMulti pExpr)
        {
            Expr rhs = Visit(pExpr.Operator);
            Expr lhs = Visit(pExpr.Left);
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs);
        }

        /////////////////////////////////////////////////////////////////////////////////
        // Expression types.

        protected override Expr VisitBOUNDLAMBDA(ExprBoundLambda anonmeth)
        {
            Debug.Assert(anonmeth != null);

            ExprBoundLambda prevAnonMeth = currentAnonMeth;
            currentAnonMeth = anonmeth;
            MethodSymbol lambdaMethod = GetPreDefMethod(PREDEFMETH.PM_EXPRESSION_LAMBDA);

            CType delegateType = anonmeth.DelegateType;
            TypeArray lambdaTypeParams = GetSymbolLoader().getBSymmgr().AllocParams(1, new CType[] { delegateType });
            AggregateType expressionType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_EXPRESSION);
            MethWithInst mwi = new MethWithInst(lambdaMethod, expressionType, lambdaTypeParams);
            Expr createParameters = CreateWraps(anonmeth);
            Expr body = RewriteLambdaBody(anonmeth);
            Expr parameters = RewriteLambdaParameters(anonmeth);
            Expr args = GetExprFactory().CreateList(body, parameters);
            CType typeRet = GetSymbolLoader().GetTypeManager().SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs);
            ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
            ExprCall call = GetExprFactory().CreateCall(0, typeRet, args, pMemGroup, mwi);
            Expr callLambda = call;

            call.PredefinedMethod = PREDEFMETH.PM_EXPRESSION_LAMBDA;

            currentAnonMeth = prevAnonMeth;
            if (createParameters != null)
            {
                callLambda = GetExprFactory().CreateSequence(createParameters, callLambda);
            }
            Expr expr = DestroyWraps(anonmeth, callLambda);
            // If we are already inside an expression tree rewrite and this is an expression tree lambda
            // then it needs to be quoted.
            if (currentAnonMeth != null)
            {
                expr = GenerateCall(PREDEFMETH.PM_EXPRESSION_QUOTE, expr);
            }
            return expr;
        }
        protected override Expr VisitCONSTANT(ExprConstant expr)
        {
            Debug.Assert(expr != null);
            return GenerateConstant(expr);
        }
        protected override Expr VisitLOCAL(ExprLocal local)
        {
            Debug.Assert(local != null);
            Debug.Assert(!local.Local.isThis);
            // this is true for all parameters of an expression lambda
            if (local.Local.wrap != null)
            {
                return local.Local.wrap;
            }
            Debug.Assert(local.Local.fUsedInAnonMeth);
            return GetExprFactory().CreateHoistedLocalInExpression();
        }
        protected override Expr VisitFIELD(ExprField expr)
        {
            Debug.Assert(expr != null);
            Expr pObject;
            if (expr.OptionalObject== null)
            {
                pObject = GetExprFactory().CreateNull();
            }
            else
            {
                pObject = Visit(expr.OptionalObject);
            }
            ExprFieldInfo pFieldInfo = GetExprFactory().CreateFieldInfo(expr.FieldWithType.Field(), expr.FieldWithType.GetType());
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_FIELD, pObject, pFieldInfo);
        }
        protected override Expr VisitUSERDEFINEDCONVERSION(ExprUserDefinedConversion expr)
        {
            Debug.Assert(expr != null);
            return GenerateUserDefinedConversion(expr, expr.Argument);
        }
        protected override Expr VisitCAST(ExprCast pExpr)
        {
            Debug.Assert(pExpr != null);

            Expr pArgument = pExpr.Argument;

            // If we have generated an identity cast or reference cast to a base class
            // we can omit the cast.
            if (pArgument.Type == pExpr.Type ||
                    SymbolLoader.IsBaseClassOfClass(pArgument.Type, pExpr.Type) ||
                    CConversions.FImpRefConv(GetSymbolLoader(), pArgument.Type, pExpr.Type))
            {
                return Visit(pArgument);
            }

            // If we have a cast to PredefinedType.PT_G_EXPRESSION and the thing that we're casting is
            // a EXPRBOUNDLAMBDA that is an expression tree, then just visit the expression tree.
            if (pExpr.Type != null &&
                    pExpr.Type.isPredefType(PredefinedType.PT_G_EXPRESSION) &&
                    pArgument is ExprBoundLambda)
            {
                return Visit(pArgument);
            }

            Expr result = GenerateConversion(pArgument, pExpr.Type, pExpr.isChecked());
            if ((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0)
            {
                // Propagate the unbox flag to the call for the ExpressionTreeCallRewriter.
                result.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME;
            }
            return result;
        }
        protected override Expr VisitCONCAT(ExprConcat expr)
        {
            Debug.Assert(expr != null);
            PREDEFMETH pdm;
            if (expr.FirstArgument.Type.isPredefType(PredefinedType.PT_STRING) && expr.SecondArgument.Type.isPredefType(PredefinedType.PT_STRING))
            {
                pdm = PREDEFMETH.PM_STRING_CONCAT_STRING_2;
            }
            else
            {
                pdm = PREDEFMETH.PM_STRING_CONCAT_OBJECT_2;
            }
            Expr p1 = Visit(expr.FirstArgument);
            Expr p2 = Visit(expr.SecondArgument);
            MethodSymbol method = GetPreDefMethod(pdm);
            Expr methodInfo = GetExprFactory().CreateMethodInfo(method, GetSymbolLoader().GetPredefindType(PredefinedType.PT_STRING), null);
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, p1, p2, methodInfo);
        }
        protected override Expr VisitBINOP(ExprBinOp expr)
        {
            Debug.Assert(expr != null);
            if (expr.UserDefinedCallMethod != null)
            {
                return GenerateUserDefinedBinaryOperator(expr);
            }
            else
            {
                return GenerateBuiltInBinaryOperator(expr);
            }
        }
        protected override Expr VisitUNARYOP(ExprUnaryOp pExpr)
        {
            Debug.Assert(pExpr != null);
            if (pExpr.UserDefinedCallMethod != null)
            {
                return GenerateUserDefinedUnaryOperator(pExpr);
            }
            else
            {
                return GenerateBuiltInUnaryOperator(pExpr);
            }
        }
        protected override Expr VisitARRAYINDEX(ExprArrayIndex pExpr)
        {
            Debug.Assert(pExpr != null);
            Expr arr = Visit(pExpr.Array);
            Expr args = GenerateIndexList(pExpr.Index);
            if (args is ExprList)
            {
                Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
                return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, arr, Params);
            }
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, arr, args);
        }

        protected override Expr VisitCALL(ExprCall expr)
        {
            Debug.Assert(expr != null);
            switch (expr.NullableCallLiftKind)
            {
                default:
                    break;
                case NullableCallLiftKind.NullableIntermediateConversion:
                case NullableCallLiftKind.NullableConversion:
                case NullableCallLiftKind.NullableConversionConstructor:
                    return GenerateConversion(expr.OptionalArguments, expr.Type, expr.isChecked());
                case NullableCallLiftKind.NotLiftedIntermediateConversion:
                case NullableCallLiftKind.UserDefinedConversion:
                    return GenerateUserDefinedConversion(expr.OptionalArguments, expr.Type, expr.MethWithInst);
            }

            if (expr.MethWithInst.Meth().IsConstructor())
            {
                return GenerateConstructor(expr);
            }

            ExprMemberGroup memberGroup = expr.MemberGroup;
            if (memberGroup.IsDelegate)
            {
                return GenerateDelegateInvoke(expr);
            }

            Expr pObject;
            if (expr.MethWithInst.Meth().isStatic || expr.MemberGroup.OptionalObject== null)
            {
                pObject = GetExprFactory().CreateNull();
            }
            else
            {
                pObject = expr.MemberGroup.OptionalObject;

                // If we have, say, an int? which is the object of a call to ToString
                // then we do NOT want to generate ((object)i).ToString() because that
                // will convert a null-valued int? to a null object.  Rather what we want
                // to do is box it to a ValueType and call ValueType.ToString.
                //
                // To implement this we say that if the object of the call is an implicit boxing cast
                // then just generate the object, not the cast.  If the cast is explicit in the
                // source code then it will be an EXPLICITCAST and we will visit it normally.
                //
                // It might be better to rewrite the expression tree API so that it
                // can handle in the general case all implicit boxing conversions. Right now it
                // requires that all arguments to a call that need to be boxed be explicitly boxed.

                if (pObject != null && pObject is ExprCast cast && cast.IsBoxingCast)
                {
                    pObject = cast.Argument;
                }
                pObject = Visit(pObject);
            }
            Expr methodInfo = GetExprFactory().CreateMethodInfo(expr.MethWithInst);
            Expr args = GenerateArgsList(expr.OptionalArguments);
            Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
            PREDEFMETH pdm = PREDEFMETH.PM_EXPRESSION_CALL;
            Debug.Assert(!expr.MethWithInst.Meth().isVirtual || expr.MemberGroup.OptionalObject != null);

            return GenerateCall(pdm, pObject, methodInfo, Params);
        }
        protected override Expr VisitPROP(ExprProperty expr)
        {
            Debug.Assert(expr != null);
            Expr pObject;
            if (expr.PropWithTypeSlot.Prop().isStatic || expr.MemberGroup.OptionalObject== null)
            {
                pObject = GetExprFactory().CreateNull();
            }
            else
            {
                pObject = Visit(expr.MemberGroup.OptionalObject);
            }
            Expr propInfo = GetExprFactory().CreatePropertyInfo(expr.PropWithTypeSlot.Prop(), expr.PropWithTypeSlot.GetType());
            if (expr.OptionalArguments != null)
            {
                // It is an indexer property.  Turn it into a virtual method call.
                Expr args = GenerateArgsList(expr.OptionalArguments);
                Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
                return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo, Params);
            }
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo);
        }
        protected override Expr VisitARRINIT(ExprArrayInit expr)
        {
            Debug.Assert(expr != null);
            // POSSIBLE ERROR: Multi-d should be an error?
            Expr pTypeOf = CreateTypeOf(((ArrayType)expr.Type).GetElementType());
            Expr args = GenerateArgsList(expr.OptionalArguments);
            Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, pTypeOf, Params);
        }
        protected override Expr VisitZEROINIT(ExprZeroInit expr)
        {
            Debug.Assert(expr != null);
            return GenerateConstant(expr);
        }
        protected override Expr VisitTYPEOF(ExprTypeOf expr)
        {
            Debug.Assert(expr != null);
            return GenerateConstant(expr);
        }

        private Expr GenerateDelegateInvoke(ExprCall expr)
        {
            Debug.Assert(expr != null);
            ExprMemberGroup memberGroup = expr.MemberGroup;
            Debug.Assert(memberGroup.IsDelegate);
            Expr oldObject = memberGroup.OptionalObject;
            Debug.Assert(oldObject != null);
            Expr pObject = Visit(oldObject);
            Expr args = GenerateArgsList(expr.OptionalArguments);
            Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_INVOKE, pObject, Params);
        }

        private Expr GenerateBuiltInBinaryOperator(ExprBinOp expr)
        {
            Debug.Assert(expr != null);
            PREDEFMETH pdm;

            switch (expr.Kind)
            {
                case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT; break;
                case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT; break;
                case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR; break;
                case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR; break;
                case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND; break;
                case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO; break;
                case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE; break;
                case ExpressionKind.StringEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break;
                case ExpressionKind.Eq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break;
                case ExpressionKind.StringNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break;
                case ExpressionKind.NotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break;
                case ExpressionKind.GreaterThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL; break;
                case ExpressionKind.LessThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL; break;
                case ExpressionKind.LessThan: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN; break;
                case ExpressionKind.GreaterThan: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN; break;
                case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO; break;
                case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE; break;
                case ExpressionKind.Multiply:
                    pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED : PREDEFMETH.PM_EXPRESSION_MULTIPLY;
                    break;
                case ExpressionKind.Subtract:
                    pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED : PREDEFMETH.PM_EXPRESSION_SUBTRACT;
                    break;
                case ExpressionKind.Add:
                    pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED : PREDEFMETH.PM_EXPRESSION_ADD;
                    break;

                default:
                    throw Error.InternalCompilerError();
            }
            Expr origL = expr.OptionalLeftChild;
            Expr origR = expr.OptionalRightChild;
            Debug.Assert(origL != null);
            Debug.Assert(origR != null);
            CType typeL = origL.Type;
            CType typeR = origR.Type;

            Expr newL = Visit(origL);
            Expr newR = Visit(origR);

            bool didEnumConversion = false;
            CType convertL = null;
            CType convertR = null;

            if (typeL.isEnumType())
            {
                // We have already inserted casts if not lifted, so we should never see an enum.
                Debug.Assert(expr.IsLifted);
                convertL = GetSymbolLoader().GetTypeManager().GetNullable(typeL.underlyingEnumType());
                typeL = convertL;
                didEnumConversion = true;
            }
            else if (typeL is NullableType nubL && nubL.UnderlyingType.isEnumType())
            {
                Debug.Assert(expr.IsLifted);
                convertL = GetSymbolLoader().GetTypeManager().GetNullable(nubL.UnderlyingType.underlyingEnumType());
                typeL = convertL;
                didEnumConversion = true;
            }
            if (typeR.isEnumType())
            {
                Debug.Assert(expr.IsLifted);
                convertR = GetSymbolLoader().GetTypeManager().GetNullable(typeR.underlyingEnumType());
                typeR = convertR;
                didEnumConversion = true;
            }
            else if (typeR is NullableType nubR && nubR.UnderlyingType.isEnumType())
            {
                Debug.Assert(expr.IsLifted);
                convertR = GetSymbolLoader().GetTypeManager().GetNullable(nubR.UnderlyingType.underlyingEnumType());
                typeR = convertR;
                didEnumConversion = true;
            }
            if (typeL is NullableType nubL2 && nubL2.UnderlyingType == typeR)
            {
                convertR = typeL;
            }
            if (typeR is NullableType nubR2 && nubR2.UnderlyingType == typeL)
            {
                convertL = typeR;
            }

            if (convertL != null)
            {
                newL = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newL, CreateTypeOf(convertL));
            }
            if (convertR != null)
            {
                newR = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newR, CreateTypeOf(convertR));
            }

            Expr call = GenerateCall(pdm, newL, newR);

            if (didEnumConversion && expr.Type.StripNubs().isEnumType())
            {
                call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(expr.Type));
            }

            return call;
        }

        private Expr GenerateBuiltInUnaryOperator(ExprUnaryOp expr)
        {
            Debug.Assert(expr != null);
            PREDEFMETH pdm;
            switch (expr.Kind)
            {
                case ExpressionKind.UnaryPlus:
                    return Visit(expr.Child);
                case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break;
                case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break;
                case ExpressionKind.Negate:
                    pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED : PREDEFMETH.PM_EXPRESSION_NEGATE;
                    break;
                default:
                    throw Error.InternalCompilerError();
            }
            Expr origOp = expr.Child;

            return GenerateBuiltInUnaryOperator(pdm, origOp, expr);
        }

        private Expr GenerateBuiltInUnaryOperator(PREDEFMETH pdm, Expr pOriginalOperator, Expr pOperator)
        {
            Expr op = Visit(pOriginalOperator);
            bool isNullableEnum = pOriginalOperator.Type is NullableType nub && nub.underlyingType().isEnumType();
            if (isNullableEnum)
            {
                Debug.Assert(pOperator.Kind == ExpressionKind.BitwiseNot); // The only built-in unary operator defined on nullable enum.
                CType underlyingType = pOriginalOperator.Type.StripNubs().underlyingEnumType();
                CType nullableType = GetSymbolLoader().GetTypeManager().GetNullable(underlyingType);
                op = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, op, CreateTypeOf(nullableType));
            }

            Expr call = GenerateCall(pdm, op);
            if (isNullableEnum)
            {
                call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(pOperator.Type));
            }

            return call;
        }

        private Expr GenerateUserDefinedBinaryOperator(ExprBinOp expr)
        {
            Debug.Assert(expr != null);
            PREDEFMETH pdm;

            switch (expr.Kind)
            {
                case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED; break;
                case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED; break;
                case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED; break;
                case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED; break;
                case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED; break;
                case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED; break;
                case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED; break;
                case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED; break;
                case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED; break;
                case ExpressionKind.StringEq:
                case ExpressionKind.StringNotEq:
                case ExpressionKind.DelegateEq:
                case ExpressionKind.DelegateNotEq:
                case ExpressionKind.Eq:
                case ExpressionKind.NotEq:
                case ExpressionKind.GreaterThanOrEqual:
                case ExpressionKind.GreaterThan:
                case ExpressionKind.LessThanOrEqual:
                case ExpressionKind.LessThan:
                    return GenerateUserDefinedComparisonOperator(expr);
                case ExpressionKind.DelegateSubtract:
                case ExpressionKind.Subtract:
                    pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED;
                    break;
                case ExpressionKind.DelegateAdd:
                case ExpressionKind.Add:
                    pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED;
                    break;
                case ExpressionKind.Multiply:
                    pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED;
                    break;
                default:
                    throw Error.InternalCompilerError();
            }
            Expr p1 = expr.OptionalLeftChild;
            Expr p2 = expr.OptionalRightChild;
            Expr udcall = expr.OptionalUserDefinedCall;
            if (udcall != null)
            {
                Debug.Assert(udcall.Kind == ExpressionKind.Call || udcall.Kind == ExpressionKind.UserLogicalOp);
                if (udcall is ExprCall ascall)
                {
                    ExprList args = (ExprList)ascall.OptionalArguments;
                    Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
                    p1 = args.OptionalElement;
                    p2 = args.OptionalNextListNode;
                }
                else
                {
                    ExprUserLogicalOp userLogOp = udcall as ExprUserLogicalOp;
                    Debug.Assert(userLogOp != null);
                    ExprList args = (ExprList)userLogOp.OperatorCall.OptionalArguments;
                    Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
                    p1 = ((ExprWrap)args.OptionalElement).OptionalExpression;
                    p2 = args.OptionalNextListNode;
                }
            }
            p1 = Visit(p1);
            p2 = Visit(p2);
            FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2);
            Expr methodInfo = GetExprFactory().CreateMethodInfo(expr.UserDefinedCallMethod);
            Expr call = GenerateCall(pdm, p1, p2, methodInfo);
            // Delegate add/subtract generates a call to Combine/Remove, which returns System.Delegate,
            // not the operand delegate CType.  We must cast to the delegate CType.
            if (expr.Kind == ExpressionKind.DelegateSubtract || expr.Kind == ExpressionKind.DelegateAdd)
            {
                Expr pTypeOf = CreateTypeOf(expr.Type);
                return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf);
            }
            return call;
        }

        private Expr GenerateUserDefinedUnaryOperator(ExprUnaryOp expr)
        {
            Debug.Assert(expr != null);
            PREDEFMETH pdm;
            Expr arg = expr.Child;
            ExprCall call = (ExprCall)expr.OptionalUserDefinedCall;
            if (call != null)
            {
                // Use the actual argument of the call; it may contain user-defined
                // conversions or be a bound lambda, and that will not be in the original
                // argument stashed away in the left child of the operator.
                arg = call.OptionalArguments;
            }
            Debug.Assert(arg != null && arg.Kind != ExpressionKind.List);
            switch (expr.Kind)
            {
                case ExpressionKind.True:
                case ExpressionKind.False:
                    return Visit(call);
                case ExpressionKind.UnaryPlus:
                    pdm = PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED;
                    break;
                case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break;
                case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break;
                case ExpressionKind.DecimalNegate:
                case ExpressionKind.Negate:
                    pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED;
                    break;

                case ExpressionKind.Inc:
                case ExpressionKind.Dec:
                case ExpressionKind.DecimalInc:
                case ExpressionKind.DecimalDec:
                    pdm = PREDEFMETH.PM_EXPRESSION_CALL;
                    break;

                default:
                    throw Error.InternalCompilerError();
            }
            Expr op = Visit(arg);
            Expr methodInfo = GetExprFactory().CreateMethodInfo(expr.UserDefinedCallMethod);

            if (expr.Kind == ExpressionKind.Inc || expr.Kind == ExpressionKind.Dec ||
                expr.Kind == ExpressionKind.DecimalInc || expr.Kind == ExpressionKind.DecimalDec)
            {
                return GenerateCall(pdm, null, methodInfo, GenerateParamsArray(op, PredefinedType.PT_EXPRESSION));
            }
            return GenerateCall(pdm, op, methodInfo);
        }

        private Expr GenerateUserDefinedComparisonOperator(ExprBinOp expr)
        {
            Debug.Assert(expr != null);
            PREDEFMETH pdm;

            switch (expr.Kind)
            {
                case ExpressionKind.StringEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break;
                case ExpressionKind.StringNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break;
                case ExpressionKind.DelegateEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break;
                case ExpressionKind.DelegateNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break;
                case ExpressionKind.Eq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break;
                case ExpressionKind.NotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break;
                case ExpressionKind.LessThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED; break;
                case ExpressionKind.LessThan: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED; break;
                case ExpressionKind.GreaterThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED; break;
                case ExpressionKind.GreaterThan: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED; break;
                default:
                    throw Error.InternalCompilerError();
            }
            Expr p1 = expr.OptionalLeftChild;
            Expr p2 = expr.OptionalRightChild;
            if (expr.OptionalUserDefinedCall != null)
            {
                ExprCall udcall = (ExprCall)expr.OptionalUserDefinedCall;
                ExprList args = (ExprList)udcall.OptionalArguments;
                Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);

                p1 = args.OptionalElement;
                p2 = args.OptionalNextListNode;
            }
            p1 = Visit(p1);
            p2 = Visit(p2);
            FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2);
            Expr lift = GetExprFactory().CreateBoolConstant(false); // We never lift to null in C#.
            Expr methodInfo = GetExprFactory().CreateMethodInfo(expr.UserDefinedCallMethod);
            return GenerateCall(pdm, p1, p2, lift, methodInfo);
        }

        private Expr RewriteLambdaBody(ExprBoundLambda anonmeth)
        {
            Debug.Assert(anonmeth != null);
            Debug.Assert(anonmeth.OptionalBody != null);
            Debug.Assert(anonmeth.OptionalBody.OptionalStatements != null);
            // There ought to be no way to get an empty statement block successfully converted into an expression tree.
            Debug.Assert(anonmeth.OptionalBody.OptionalStatements.OptionalNextStatement== null);

            ExprBlock body = anonmeth.OptionalBody;

            // The most likely case:
            if (body.OptionalStatements is ExprReturn ret)
            {
                Debug.Assert(ret.OptionalObject != null);
                return Visit(ret.OptionalObject);
            }
            // This can only if it is a void delegate and this is a void expression, such as a call to a void method
            // or something like Expression<Action<Foo>> e = (Foo f) => f.MyEvent += MyDelegate;

            throw Error.InternalCompilerError();
        }

        private Expr RewriteLambdaParameters(ExprBoundLambda anonmeth)
        {
            Debug.Assert(anonmeth != null);

            // new ParameterExpression[2] {Parameter(typeof(type1), name1), Parameter(typeof(type2), name2)}

            Expr paramArrayInitializerArgs = null;
            Expr paramArrayInitializerArgsTail = paramArrayInitializerArgs;

            for (Symbol sym = anonmeth.ArgumentScope; sym != null; sym = sym.nextChild)
            {
                if (!(sym is LocalVariableSymbol local))
                {
                    continue;
                }

                if (local.isThis)
                {
                    continue;
                }
                GetExprFactory().AppendItemToList(local.wrap, ref paramArrayInitializerArgs, ref paramArrayInitializerArgsTail);
            }

            return GenerateParamsArray(paramArrayInitializerArgs, PredefinedType.PT_PARAMETEREXPRESSION);
        }

        private Expr GenerateConversion(Expr arg, CType CType, bool bChecked)
        {
            return GenerateConversionWithSource(Visit(arg), CType, bChecked || arg.isChecked());
        }

        private Expr GenerateConversionWithSource(Expr pTarget, CType pType, bool bChecked)
        {
            PREDEFMETH pdm = bChecked ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT;
            Expr pTypeOf = CreateTypeOf(pType);
            return GenerateCall(pdm, pTarget, pTypeOf);
        }

        private Expr GenerateValueAccessConversion(Expr pArgument)
        {
            Debug.Assert(pArgument != null);
            CType pStrippedTypeOfArgument = pArgument.Type.StripNubs();
            Expr pStrippedTypeExpr = CreateTypeOf(pStrippedTypeOfArgument);
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, Visit(pArgument), pStrippedTypeExpr);
        }

        private Expr GenerateUserDefinedConversion(Expr arg, CType type, MethWithInst method)
        {
            Expr target = Visit(arg);
            return GenerateUserDefinedConversion(arg, type, target, method);
        }

        private Expr GenerateUserDefinedConversion(Expr arg, CType CType, Expr target, MethWithInst method)
        {
            // The user-defined explicit conversion from enum? to decimal or decimal? requires
            // that we convert the enum? to its nullable underlying CType.
            if (isEnumToDecimalConversion(arg.Type, CType))
            {
                // Special case: If we have enum? to decimal? then we need to emit
                // a conversion from enum? to its nullable underlying CType first.
                // This is unfortunate; we ought to reorganize how conversions are
                // represented in the Expr tree so that this is more transparent.

                // converting an enum to its underlying CType never fails, so no need to check it.
                CType underlyingType = arg.Type.StripNubs().underlyingEnumType();
                CType nullableType = GetSymbolLoader().GetTypeManager().GetNullable(underlyingType);
                Expr typeofNubEnum = CreateTypeOf(nullableType);
                target = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, target, typeofNubEnum);
            }

            // If the methodinfo does not return the target CType AND this is not a lifted conversion
            // from one value CType to another, then we need to wrap the whole thing in another conversion,
            // e.g. if we have a user-defined conversion from int to S? and we have (S)myint, then we need to generate
            // Convert(Convert(myint, typeof(S?), op_implicit), typeof(S))

            CType pMethodReturnType = GetSymbolLoader().GetTypeManager().SubstType(method.Meth().RetType,
                method.GetType(), method.TypeArgs);
            bool fDontLiftReturnType = (pMethodReturnType == CType || (IsNullableValueType(arg.Type) && IsNullableValueType(CType)));

            Expr typeofInner = CreateTypeOf(fDontLiftReturnType ? CType : pMethodReturnType);
            Expr methodInfo = GetExprFactory().CreateMethodInfo(method);
            PREDEFMETH pdmInner = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED;
            Expr callUserDefinedConversion = GenerateCall(pdmInner, target, typeofInner, methodInfo);

            if (fDontLiftReturnType)
            {
                return callUserDefinedConversion;
            }

            PREDEFMETH pdmOuter = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT;
            Expr typeofOuter = CreateTypeOf(CType);
            return GenerateCall(pdmOuter, callUserDefinedConversion, typeofOuter);
        }

        private Expr GenerateUserDefinedConversion(ExprUserDefinedConversion pExpr, Expr pArgument)
        {
            Expr pCastCall = pExpr.UserDefinedCall;
            Expr pCastArgument = pExpr.Argument;
            Expr pConversionSource;

            if (!isEnumToDecimalConversion(pArgument.Type, pExpr.Type)
                && IsNullableValueAccess(pCastArgument, pArgument))
            {
                // We have an implicit conversion of nullable CType to the value CType, generate a convert node for it.
                pConversionSource = GenerateValueAccessConversion(pArgument);
            }
            else
            {
                ExprCall call = pCastCall as ExprCall;
                Expr pUDConversion = call?.PConversions;
                if (pUDConversion != null)
                {
                    if (pUDConversion is ExprCall convCall)
                    {
                        Expr pUDConversionArgument = convCall.OptionalArguments;
                        if (IsNullableValueAccess(pUDConversionArgument, pArgument))
                        {
                            pConversionSource = GenerateValueAccessConversion(pArgument);
                        }
                        else
                        {
                            pConversionSource = Visit(pUDConversionArgument);
                        }

                        return GenerateConversionWithSource(pConversionSource, pCastCall.Type, call.isChecked());
                    }

                    // This can happen if we have a UD conversion from C to, say, int,
                    // and we have an explicit cast to decimal?. The conversion should
                    // then be bound as two chained user-defined conversions.
                    Debug.Assert(pUDConversion is ExprUserDefinedConversion);

                    // Just recurse.
                    return GenerateUserDefinedConversion((ExprUserDefinedConversion)pUDConversion, pArgument);
                }

                pConversionSource = Visit(pCastArgument);
            }

            return GenerateUserDefinedConversion(pCastArgument, pExpr.Type, pConversionSource, pExpr.UserDefinedCallMethod);
        }

        private Expr GenerateParameter(string name, CType CType)
        {
            GetSymbolLoader().GetPredefindType(PredefinedType.PT_STRING);  // force an ensure state
            ExprConstant nameString = GetExprFactory().CreateStringConstant(name);
            ExprTypeOf pTypeOf = CreateTypeOf(CType);
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_PARAMETER, pTypeOf, nameString);
        }

        private MethodSymbol GetPreDefMethod(PREDEFMETH pdm)
        {
            return GetSymbolLoader().getPredefinedMembers().GetMethod(pdm);
        }

        private ExprTypeOf CreateTypeOf(CType CType)
        {
            return GetExprFactory().CreateTypeOf(CType);
        }

        private Expr CreateWraps(ExprBoundLambda anonmeth)
        {
            Expr sequence = null;
            for (Symbol sym = anonmeth.ArgumentScope.firstChild; sym != null; sym = sym.nextChild)
            {
                if (!(sym is LocalVariableSymbol local))
                {
                    continue;
                }

                if (local.isThis)
                {
                    continue;
                }
                Debug.Assert(anonmeth.OptionalBody != null);
                Expr create = GenerateParameter(local.name.Text, local.GetType());
                local.wrap = GetExprFactory().CreateWrap(create);
                Expr save = GetExprFactory().CreateSave(local.wrap);
                if (sequence == null)
                {
                    sequence = save;
                }
                else
                {
                    sequence = GetExprFactory().CreateSequence(sequence, save);
                }
            }

            return sequence;
        }

        private Expr DestroyWraps(ExprBoundLambda anonmeth, Expr sequence)
        {
            for (Symbol sym = anonmeth.ArgumentScope; sym != null; sym = sym.nextChild)
            {
                if (!(sym is LocalVariableSymbol local))
                {
                    continue;
                }

                if (local.isThis)
                {
                    continue;
                }
                Debug.Assert(local.wrap != null);
                Debug.Assert(anonmeth.OptionalBody != null);
                Expr freeWrap = GetExprFactory().CreateWrap(local.wrap);
                sequence = GetExprFactory().CreateReverseSequence(sequence, freeWrap);
            }
            return sequence;
        }

        private Expr GenerateConstructor(ExprCall expr)
        {
            Debug.Assert(expr != null);
            Debug.Assert(expr.MethWithInst.Meth().IsConstructor());
            Expr constructorInfo = GetExprFactory().CreateMethodInfo(expr.MethWithInst);
            Expr args = GenerateArgsList(expr.OptionalArguments);
            Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
            return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params);
        }

        private Expr GenerateArgsList(Expr oldArgs)
        {
            Expr newArgs = null;
            Expr newArgsTail = newArgs;
            for (ExpressionIterator it = new ExpressionIterator(oldArgs); !it.AtEnd(); it.MoveNext())
            {
                Expr oldArg = it.Current();
                GetExprFactory().AppendItemToList(Visit(oldArg), ref newArgs, ref newArgsTail);
            }
            return newArgs;
        }

        private Expr GenerateIndexList(Expr oldIndices)
        {
            CType intType = symbolLoader.GetPredefindType(PredefinedType.PT_INT);

            Expr newIndices = null;
            Expr newIndicesTail = newIndices;
            for (ExpressionIterator it = new ExpressionIterator(oldIndices); !it.AtEnd(); it.MoveNext())
            {
                Expr newIndex = it.Current();
                if (newIndex.Type != intType)
                {
                    ExprClass exprType = expressionFactory.CreateClass(intType);
                    newIndex = expressionFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, exprType, newIndex);
                    newIndex.Flags |= EXPRFLAG.EXF_CHECKOVERFLOW;
                }
                Expr rewrittenIndex = Visit(newIndex);
                expressionFactory.AppendItemToList(rewrittenIndex, ref newIndices, ref newIndicesTail);
            }
            return newIndices;
        }

        private Expr GenerateConstant(Expr expr)
        {
            EXPRFLAG flags = 0;

            AggregateType pObject = GetSymbolLoader().GetPredefindType(PredefinedType.PT_OBJECT);

            if (expr.Type is NullType)
            {
                ExprTypeOf pTypeOf = CreateTypeOf(pObject);
                return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, expr, pTypeOf);
            }

            AggregateType stringType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_STRING);
            if (expr.Type != stringType)
            {
                flags = EXPRFLAG.EXF_BOX;
            }

            ExprClass objectType = GetExprFactory().CreateClass(pObject);
            ExprCast cast = GetExprFactory().CreateCast(flags, objectType, expr);
            ExprTypeOf pTypeOf2 = CreateTypeOf(expr.Type);

            return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, cast, pTypeOf2);
        }

        private ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1)
        {
            MethodSymbol method = GetPreDefMethod(pdm);
            // this should be enforced in an earlier pass and the transform pass should not
            // be handling this error
            if (method == null)
                return null;
            AggregateType expressionType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_EXPRESSION);
            MethWithInst mwi = new MethWithInst(method, expressionType);
            ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
            ExprCall call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, arg1, pMemGroup, mwi);
            call.PredefinedMethod = pdm;
            return call;
        }

        private ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2)
        {
            MethodSymbol method = GetPreDefMethod(pdm);
            if (method == null)
                return null;
            AggregateType expressionType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_EXPRESSION);
            Expr args = GetExprFactory().CreateList(arg1, arg2);
            MethWithInst mwi = new MethWithInst(method, expressionType);
            ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
            ExprCall call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
            call.PredefinedMethod = pdm;
            return call;
        }

        private ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3)
        {
            MethodSymbol method = GetPreDefMethod(pdm);
            if (method == null)
                return null;
            AggregateType expressionType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_EXPRESSION);
            Expr args = GetExprFactory().CreateList(arg1, arg2, arg3);
            MethWithInst mwi = new MethWithInst(method, expressionType);
            ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
            ExprCall call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
            call.PredefinedMethod = pdm;
            return call;
        }

        private ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3, Expr arg4)
        {
            MethodSymbol method = GetPreDefMethod(pdm);
            if (method == null)
                return null;
            AggregateType expressionType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_EXPRESSION);
            Expr args = GetExprFactory().CreateList(arg1, arg2, arg3, arg4);
            MethWithInst mwi = new MethWithInst(method, expressionType);
            ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
            ExprCall call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
            call.PredefinedMethod = pdm;
            return call;
        }

        private ExprArrayInit GenerateParamsArray(Expr args, PredefinedType pt)
        {
            int parameterCount = ExpressionIterator.Count(args);
            AggregateType paramsArrayElementType = GetSymbolLoader().GetPredefindType(pt);
            ArrayType paramsArrayType = GetSymbolLoader().GetTypeManager().GetArray(paramsArrayElementType, 1, true);
            ExprConstant paramsArrayArg = GetExprFactory().CreateIntegerConstant(parameterCount);
            return GetExprFactory().CreateArrayInit(paramsArrayType, args, paramsArrayArg, new int[] { parameterCount }, parameterCount);
        }

        private void FixLiftedUserDefinedBinaryOperators(ExprBinOp expr, ref Expr pp1, ref Expr pp2)
        {
            // If we have lifted T1 op T2 to T1? op T2?, and we have an expression T1 op T2? or T1? op T2 then
            // we need to ensure that the unlifted actual arguments are promoted to their nullable CType.
            Debug.Assert(expr != null);
            Debug.Assert(pp1 != null);
            Debug.Assert(pp1 != null);
            Debug.Assert(pp2 != null);
            Debug.Assert(pp2 != null);
            MethodSymbol method = expr.UserDefinedCallMethod.Meth();
            Expr orig1 = expr.OptionalLeftChild;
            Expr orig2 = expr.OptionalRightChild;
            Debug.Assert(orig1 != null && orig2 != null);
            Expr new1 = pp1;
            Expr new2 = pp2;
            CType fptype1 = method.Params[0];
            CType fptype2 = method.Params[1];
            CType aatype1 = orig1.Type;
            CType aatype2 = orig2.Type;
            // Is the operator even a candidate for lifting?
            if (!(fptype1 is AggregateType fat1)
                || !fat1.getAggregate().IsValueType()
                || !(fptype2 is AggregateType fat2)
                || !fat2.getAggregate().IsValueType())
            {
                return;
            }

            CType nubfptype1 = GetSymbolLoader().GetTypeManager().GetNullable(fptype1);
            CType nubfptype2 = GetSymbolLoader().GetTypeManager().GetNullable(fptype2);
            // If we have null op X, or T1 op T2?, or T1 op null, lift first arg to T1?
            if (aatype1 is NullType || aatype1 == fptype1 && (aatype2 == nubfptype2 || aatype2 is NullType))
            {
                new1 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new1, CreateTypeOf(nubfptype1));
            }

            // If we have X op null, or T1? op T2, or null op T2, lift second arg to T2?
            if (aatype2 is NullType || aatype2 == fptype2 && (aatype1 == nubfptype1 || aatype1 is NullType))
            {
                new2 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new2, CreateTypeOf(nubfptype2));
            }
            pp1 = new1;
            pp2 = new2;
        }

        private bool IsNullableValueType(CType pType) =>
            pType is NullableType && pType.StripNubs() is AggregateType agg && agg.getAggregate().IsValueType();

        private bool IsNullableValueAccess(Expr pExpr, Expr pObject)
        {
            Debug.Assert(pExpr != null);
            return pExpr is ExprProperty prop && prop.MemberGroup.OptionalObject == pObject && pObject.Type is NullableType;
        }

        private static bool isEnumToDecimalConversion(CType argtype, CType desttype) =>
            argtype.StripNubs().isEnumType() && desttype.StripNubs().isPredefType(PredefinedType.PT_DECIMAL);
    }
}


text:
def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b

print "Let's do some math with just functions!"

#in the above functions, the variable are computed togeter and set equal to the following variables, but when returned, the computed values are not returned
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)

#A puzzle for the extra credit, type it in anyway
print "Here is a puzzle."

#this is equal to (35 + (72 - (180 * (50 / 2))))
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"

redpajama_set_name: RedPajamaGithub


text:
Gnieh Tekstlib [![Build Status](https://travis-ci.org/gnieh/tekstlib.png)](https://travis-ci.org/gnieh/tekstlib)
==============

Gnieh Tekstlib is a library grouping standard classes and packages allowing people to work with texts and documents.

Tekstlib is published to sonatype and central maven repositories and is built for Scala 2.11 and 2.12.

Here is what you want to use in your SBT file

```scala
libraryDependencies += "org.gnieh" %% "tekstlib" % "0.1.1"
```

Package Structure
-----------------

 - `gnieh.diff` diff manipulation,
 - `gnieh.matching` string matching algorithms (exact or fuzzy),
 - `gnieh.hyphen` hyphenation for text in any language,
 - `gnieh.string` strings manipulation for text processing,
 - `gnieh.mustache` lightweight mustache template processor,
 - `gnieh.pp` pretty printing related classes,
 - `gnieh.regex` regular expressions manipulation.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Symbio.Base.Model.WebServices.Contracts
{
    public interface IWebRequestFactory
    {
        IWebRequest Create(string url);
    }
}


text:
package io.ray.streaming.runtime.core.processor;

import io.ray.streaming.api.collector.Collector;
import io.ray.streaming.api.context.RuntimeContext;
import io.ray.streaming.api.function.Function;
import java.io.Serializable;
import java.util.List;

public interface Processor<T> extends Serializable {

  void open(List<Collector> collectors, RuntimeContext runtimeContext);

  void process(T t);

  /**
   * See {@link Function#saveCheckpoint()}.
   */
  Serializable saveCheckpoint();

  /**
   * See {@link Function#loadCheckpoint(Serializable)}.
   */
  void loadCheckpoint(Serializable checkpointObject);

  void close();
}


text:
import * as React from 'react';
import { expect } from 'chai';
import { createRenderer, screen } from 'test/utils';
import { unstable_useForkRef as useForkRef } from '.';

describe('useForkRef', () => {
  const { render } = createRenderer();

  it('returns a single ref-setter function that forks the ref to its inputs', () => {
    function Component(props) {
      const { innerRef } = props;
      const [ownRefCurrent, ownRef] = React.useState(null);

      const handleRef = useForkRef(innerRef, ownRef);

      return
{ownRefCurrent ? 'has a ref' : 'has no ref'}
;
    }

    const outerRef = React.createRef();

    expect(() => {
      render(<Component innerRef={outerRef} />);
    }).not.toErrorDev();
    expect(outerRef.current.textContent).to.equal('has a ref');
  });

  it('forks if only one of the branches requires a ref', () => {
    const Component = React.forwardRef(function Component(props, ref) {
      const [hasRef, setHasRef] = React.useState(false);
      const handleOwnRef = React.useCallback(() => setHasRef(true), []);
      const handleRef = useForkRef(handleOwnRef, ref);

      return (

          {String(hasRef)}

      );
    });

    expect(() => {
      render(<Component />);
    }).not.toErrorDev();

    expect(screen.getByTestId('hasRef')).to.have.text('true');
  });

  it('does nothing if none of the forked branches requires a ref', () => {
    const Outer = React.forwardRef(function Outer(props, ref) {
      const { children } = props;
      const handleRef = useForkRef(children.ref, ref);

      return React.cloneElement(children, { ref: handleRef });
    });

    function Inner() {
      return
;
    }

    expect(() => {
      render(
        <Outer>
          <Inner />
        </Outer>,
      );
    }).not.toErrorDev();
  });

  describe('changing refs', () => {
    function Div(props) {
      const { leftRef, rightRef, ...other } = props;
      const handleRef = useForkRef(leftRef, rightRef);

      return
;
    }

    it('handles changing from no ref to some ref', () => {
      let view;

      expect(() => {
        view = render(
);
      }).not.toErrorDev();

      const ref = React.createRef();
      expect(() => {
        view.setProps({ leftRef: ref });
      }).not.toErrorDev();
      expect(ref.current.id).to.equal('test');
    });

    it('cleans up detached refs', () => {
      const firstLeftRef = React.createRef();
      const firstRightRef = React.createRef();
      const secondRightRef = React.createRef();
      let view;

      expect(() => {
        view = render(
);
      }).not.toErrorDev();
      expect(firstLeftRef.current.id).to.equal('test');
      expect(firstRightRef.current.id).to.equal('test');
      expect(secondRightRef.current).to.equal(null);

      view.setProps({ rightRef: secondRightRef });

      expect(firstLeftRef.current.id).to.equal('test');
      expect(firstRightRef.current).to.equal(null);
      expect(secondRightRef.current.id).to.equal('test');
    });
  });
});


text:
<?php
/**
 * Created by IntelliJ IDEA.
 * User: chuxiaofeng
 * Date: 17/1/27
 * Time: 下午1:04
 */

namespace Minimalism\Scheme\Value;

class ResourceType extends Value
{
    public function __construct()
    {
    }

    public function __toString()
    {
        return "Resource";
    }
}


text:
@interface PodsDummy_Pods_Facebook_iOS_SDK_RACExtensions_ReactiveCocoa : NSObject
@end
@implementation PodsDummy_Pods_Facebook_iOS_SDK_RACExtensions_ReactiveCocoa
@end


text:
#pragma once

#include <core/reflection/TypeInfo.h>

#include <iostream>
#include <string>
#include <core/collection/containers/Set.h>

namespace nspace{

  /*
  DS_META_TRIVIAL_TYPE(int);
  DS_META_TRIVIAL_TYPE(double);
  DS_META_TRIVIAL_TYPE(bool);
  DS_META_TRIVIAL_TYPE(float);
  DS_META_TRIVIAL_TYPE(char);
  DS_META_TRIVIAL_TYPE(short);
  DS_META_TRIVIAL_TYPE(unsigned int);
  DS_META_TRIVIAL_TYPE(long);
  DS_META_TRIVIAL_TYPE(long long);
  DS_META_TRIVIAL_TYPE(unsigned char);

  DS_META_TRIVIAL_TYPE(std::string);

  META(std::ostream);
  META(std::istream);
  META(std::iostream);
  META(std::ifstream);
  META(std::ofstream);

  template<typename T>
  struct meta_type_name<Set<T>>{
    static const std::string & value(){
      static std::unique_ptr<std::string> ptr;
      if(!ptr){
        ptr = std::unique_ptr<std::string>(new std::string());
        std::stringstream stream;
        stream << "Set<"<<meta_type_name<TypeInfo<T>::type>::value()<<">"<<std::endl;
        *ptr = stream.str();
      }
      return *ptr;
    }
  };

/*
template<typename T> DS_TYPENAME_METAFIELD(nspace::Set<T>){

}
*/
// meta information for default types  TODO: move to DefaultTypes.  but be sure to include correclty else TypedValue has compilation problems

//template<typename T> struct getTypeNameImpl<Set<T>>{ static const  std::string & getTypeName(){ static std::string name  = "Set<T>" ;return name; } };

/*
template<typename T>
class TypeInfo<std::vector<T>>:public Type{
TEMPLATEDSINGLETON(TypeInfo,<std::vector<T> >){
setCreateInstanceFunction([](){return new std::vector<T>();});
setDeleteInstanceFunction([](void * v){delete static_cast<std::vector<T>*>(v);});

setName(DS_INLINE_STRING("std::vector<"<<typeof(T)->getName()<<">"));
}
};
//need serializers
*/
}


text:
<?php

/**
 * Git Stream Wrapper for PHP
 *
 * @category   TQ
 * @package    TQ_VCS
 * @subpackage VCS
 * @copyright  Copyright (C) 2014 by TEQneers GmbH & Co. KG
 */

namespace TQ\Vcs\Buffer;

/**
 * Interface for file buffers used in the stream wrapper
 *
 * @author     Stefan Gehrig <gehrigteqneers.de>
 * @category   TQ
 * @package    TQ_VCS
 * @subpackage VCS
 * @copyright  Copyright (C) 2014 by TEQneers GmbH & Co. KG
 */
interface FileBufferInterface
{
    /**
     * Returns the complete contents of the buffer
     *
     * @return  string
     */
    public function getBuffer();

    /**
     * Returns true if the pointer is at the end of the buffer
     *
     * @return  boolean
     */
    public function isEof();

    /**
     * Reads $count bytes from the buffer
     *
     * @param   integer     $count      The number of bytes to read
     * @return  string|null
     */
    public function read($count);

    /**
     * Writes the given date into the buffer at the current pointer position
     *
     * @param   string  $data       The data to write
     * @return  integer             The number of bytes written
     */
    public function write($data);

    /**
     * Returns the current pointer position
     *
     * @return integer
     */
    public function getPosition();

    /**
     * Sets the pointer position
     *
     * @param   integer     $position   The position in bytes
     * @param   integer     $whence     The reference from where to measure $position (SEEK_SET, SEEK_CUR or SEEK_END)
     * @return  boolean                 True if the position could be set
     */
    public function setPosition($position, $whence);

    /**
     * Returns the stat information for the buffer
     *
     * @return array
     */
    public function getStat();

    /**
     * Flushes the buffer to the storage media
     *
     * @return  boolean
     */
    public function flush();

    /**
     * Closes the buffer
     */
    public function close();
}


text:
package endpoints

import (
	"crypto/tls"
	"errors"
	"fmt"
	"math"
	"math/rand"
	"net"

	"golang.org/x/sys/unix"

	"github.com/lxc/lxd/lxd/util"
	lxdvsock "github.com/lxc/lxd/lxd/vsock"
	"github.com/lxc/lxd/shared"
)

func createVsockListener(cert *shared.CertInfo) (net.Listener, error) {
	for i := 0; i < 10; i++ {
		// Get random port between 1024 and 65535.
		port := 1024 + rand.Int31n(math.MaxUint16-1024)

		listener, err := lxdvsock.Listen(uint32(port))
		if err != nil {
			// Try a different port.
			if errors.Is(err, unix.EADDRINUSE) {
				continue
			}

			return nil, err
		}

		return tls.NewListener(listener, util.ServerTLSConfig(cert)), nil
	}

	return nil, fmt.Errorf("Failed finding free listen port for vsock listener")
}

// VsockAddress returns the network address of the vsock endpoint, or an
// empty string if there's no vsock endpoint.
func (e *Endpoints) VsockAddress() string {
	e.mu.RLock()
	defer e.mu.RUnlock()

	listener := e.listeners[vsock]
	if listener == nil {
		return ""
	}

	return listener.Addr().String()
}


text:
module Selenium
  module WebDriver
    module Support
      class Select

        #
        # @param [Element] element The select element to use
        #

        def initialize(element)
          tag_name = element.tag_name

          unless tag_name.downcase == "select"
            raise ArgumentError, "unexpected tag name #{tag_name.inspect}"
          end

          @element = element
          @multi   = ![nil, "false"].include?(element.attribute(:multiple))
        end

        #
        # Does this select element support selecting multiple options?
        #
        # @return [Boolean]
        #

        def multiple?
          @multi
        end

        #
        # Get all options for this select element
        #
        # @return [Array<Element>]
        #

        def options
          @element.find_elements :tag_name, 'option'
        end

        #
        # Get all selected options for this select element
        #
        # @return [Array<Element>]
        #

        def selected_options
          options.select { |e| e.selected? }
        end

        #
        # Get the first selected option in this select element
        #
        # @raise [Error::NoSuchElementError] if no options are selected
        # @return [Element]
        #

        def first_selected_option
          option = options.find { |e| e.selected? }
          option or raise Error::NoSuchElementError, 'no options are selected'
        end

        #
        # Select options by visible text, index or value.
        #
        # When selecting by :text, selects options that display text matching the argument. That is, when given "Bar" this
        # would select an option like:
        #
        #     <option value="foo">Bar</option>
        #
        # When slecting by :value, selects all options that have a value matching the argument. That is, when given "foo" this
        # would select an option like:
        #
        #     <option value="foo">Bar</option>
        #
        # When selecting by :index, selects the option at the given index. This is done by examining the "index" attribute of an
        # element, and not merely by counting.
        #
        # @param [:text, :index, :value] how How to find the option
        # @param [String] what What value to find the option by.
        #

        def select_by(how, what)
          case how
          when :text
            select_by_text what
          when :index
            select_by_index what
          when :value
            select_by_value what
          else
            raise ArgumentError, "can't select options by #{how.inspect}"
          end
        end

        #
        # Deselect options by visible text, index or value.
        #
        # @param [:text, :index, :value] how How to find the option
        # @param [String] what What value to find the option by.
        # @raise [Error::UnsupportedOperationError] if the element does not support multiple selections.
        #
        # @see Select#select_by
        #

        def deselect_by(how, what)
          case how
          when :text
            deselect_by_text what
          when :value
            deselect_by_value what
          when :index
            deselect_by_index what
          else
            raise ArgumentError, "can't deselect options by #{how.inspect}"
          end
        end

        #
        # Select all unselected options. Only valid if the element supports multiple selections.
        #
        # @raise [Error::UnsupportedOperationError] if the element does not support multiple selections.
        #

        def select_all
          unless multiple?
            raise Error::UnsupportedOperationError, 'you may only select all options of a multi-select'
          end

          options.each { |e| select_option e }
        end

        #
        # Deselect all selected options. Only valid if the element supports multiple selections.
        #
        # @raise [Error::UnsupportedOperationError] if the element does not support multiple selections.
        #

        def deselect_all
          unless multiple?
            raise Error::UnsupportedOperationError, 'you may only deselect all options of a multi-select'
          end

          options.each { |e| deselect_option e }
        end

        private

        def select_by_text(text)
          opts = find_by_text text

          if opts.empty?
            raise Error::NoSuchElementError, "cannot locate element with text: #{text.inspect}"
          end

          select_options opts
        end

        def select_by_index(index)
          opts = find_by_index index

          if opts.empty?
            raise Error::NoSuchElementError, "cannot locate element with index: #{index.inspect}"
          end

          select_option opts.first
        end

        def select_by_value(value)
          opts = find_by_value value

          if opts.empty?
            raise Error::NoSuchElementError, "cannot locate option with value: #{value.inspect}"
          end

          select_options opts
        end

        def deselect_by_text(text)
          unless multiple?
            raise Error::UnsupportedOperationError, 'you may only deselect option of a multi-select'
          end
          opts = find_by_text text

          if opts.empty?
            raise Error::NoSuchElementError, "cannot locate element with text: #{text.inspect}"
          end

          deselect_options opts
        end

        def deselect_by_value(value)
          unless multiple?
            raise Error::UnsupportedOperationError, 'you may only deselect option of a multi-select'
          end
          opts = find_by_value value

          if opts.empty?
            raise Error::NoSuchElementError, "cannot locate option with value: #{value.inspect}"
          end

          deselect_options opts
        end

        def deselect_by_index(index)
          unless multiple?
            raise Error::UnsupportedOperationError, 'you may only deselect option of a multi-select'
          end
          opts = find_by_index index

          if opts.empty?
            raise Error::NoSuchElementError, "cannot locate option with index: #{index}"
          end

          deselect_option opts.first
        end

        private

        def select_option(option)
          option.click unless option.selected?
        end

        def deselect_option(option)
          option.click if option.selected?
        end

        def select_options(opts)
          if multiple?
            opts.each { |o| select_option o }
          else
            select_option opts.first
          end
        end

        def deselect_options(opts)
          if multiple?
            opts.each { |o| deselect_option o }
          else
            deselect_option opts.first
          end
        end

        def find_by_text(text)
          xpath = ".//option[normalize-space(.) = #{Escaper.escape text}]"
          opts = @element.find_elements(:xpath, xpath)

          if opts.empty? && text =~ /\s+/
            longest_word = text.split(/\s+/).max_by { |item| item.length }

            if longest_word.empty?
              candidates = options
            else
              xpath = ".//option[contains(., #{Escaper.escape longest_word})]"
              candidates = @element.find_elements(:xpath, xpath)
            end

            if multiple?
              candidates.select { |option| text == option.text }
            else
              Array(candidates.find { |option| text == option.text })
            end
          else
            opts
          end
        end

        def find_by_index(index)
          index = index.to_s
          options.select { |option| option.attribute(:index) == index }
        end

        def find_by_value(value)
          @element.find_elements(:xpath, ".//option[@value = #{Escaper.escape value}]")
        end

        #
        # @api private
        #

        module Escaper
          def self.escape(str)
            if str.include?('"') && str.include?("'")
              parts = str.split('"', -1).map { |part| %{"#{part}"} }

              quoted = parts.join(%{, '"', }).
                             gsub(/^"", |, ""$/, '')

              "concat(#{quoted})"
            elsif str.include?('"')
              # escape string with just a quote into being single quoted: f"oo -> 'f"oo'
              "'#{str}'"
            else
              # otherwise return the quoted string
              %{"#{str}"}
            end
          end

        end # Escaper
      end # Select
    end # Support
  end # WebDriver
end # Selenium


text:
"""
Simple command-line calculator for variations of Shannon entropy

Try entro.py --help to see a list of options.
"""

import math, sys
from optparse import OptionParser  # ugh

class Str (str):
    def width (self, member):
        return 256

class Utf8 (unicode):
    def __new__ (self, content):
        return unicode.__new__(self, content.decode('utf-8'))
    def width (self, member):
        return 256 * len(member.encode('utf-8'))

class Nybble (str):
    def __iter__ (self):
        for i in xrange(str.__len__(self)):
            yield chr(ord(self[i])>>4)
            yield chr(ord(self[i])&15)
    def __len__ (self):
        return str.__len__(self) * 2
    def width (self, member):
        return 16

class Bit (str):
    def __iter__ (self):
        for i in xrange(str.__len__(self)):
            for b in xrange(8):
                yield chr((ord(self[i])&(2**b)) >> b)
    def __len__ (self):
        return str.__len__(self) * 8
    def width (self, member):
        return 2

def H(data, debug=False):
    entropy = 0
    count = dict()
    for c in data:
        try:
            count[c] += 1
        except KeyError:
            count[c] = 1
    for x in count:
        p_x = float(count[x])/len(data)
        if debug:
            print "# %r: p_x=%i/%i=%f; -p_x*log(p_x,%i)=%f; sum = %f" % (
                x, count[x], len(data), p_x, data.width(x),
                -p_x*math.log(p_x, data.width(x)),
                entropy - (p_x * math.log(p_x, data.width(x))))
        ######## FIXME: base should be 8 for byte entropy,
        # but unclear what exactly it should be for UTF-8
        entropy += - p_x*math.log(p_x, data.width(x))
    return entropy

def main (args):
    parser = OptionParser()
    parser.add_option('-u', '--unicode', const=Utf8,
                      help='Use UTF-8 code points as the basic input type',
                      dest='objtype', action='store_const')
    parser.add_option('-8', '--byte', const=Str, default=Str,
                      help='Use 8-bit bytes as the basic input type',
                      dest='objtype', action='store_const')
    parser.add_option('-n', '--nybble', const=Nybble,
                      help='Use nybbles as the basic input type',
                      dest='objtype', action='store_const')
    parser.add_option('-b', '--bit', const=Bit,
                      help='Use bits as the basic input type',
                      dest='objtype', action='store_const')
    parser.add_option('-v', '--verbose',
                      help='Verbose diagnostic output',
                      dest='debug', action='store_true')
    (opts, args) = parser.parse_args()

    retval = 0

    if args == []:
        args = ['-']
    for file in args:
        handle = None
        try:
            if file is '-':
                handle = sys.stdin
            else:
                handle = open(file)
            data = handle.read()
            print "%s: %f" % (file, H(opts.objtype(data),debug=opts.debug))
        except IOError:
            retval = 1
        finally:
            if handle is not None:
                handle.close()
    return retval

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))


text:
package org.woodylab.boot.pebble;

import com.mitchellbosecke.pebble.error.LoaderException;
import com.mitchellbosecke.pebble.loader.Loader;
import com.mitchellbosecke.pebble.utils.PathUtils;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

import static java.util.Objects.nonNull;

/**
 * 本想让它 Deprecated ,可是其他 Loader 都不好使,只好启用
 *
 * @author Woody @ 15-12-11 下午5:26.
 */
public class PebbleTemplateLoader implements Loader<String>, ResourceLoaderAware {

    private ResourceLoader resourceLoader;

    private String charset = Charset.forName("UTF-8").displayName();

    private String prefix;

    private String suffix;

    @Override
    public Reader getReader(final String resourceName) throws LoaderException {
        final String fullyQualifiedResourceName = getFullyQualifiedResourceName(resourceName);
        final Resource resource = resourceLoader.getResource(fullyQualifiedResourceName);
        if (resource.exists()) {
            try {
                return new InputStreamReader(resource.getInputStream(), charset);
            } catch (IOException e) {
                throw new LoaderException(e, "Failed to load template: " + fullyQualifiedResourceName);
            }
        }
        throw new LoaderException(null, "No template exists named: " + fullyQualifiedResourceName);
    }

    @Override
    public void setResourceLoader(final ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    private String getFullyQualifiedResourceName(final String resourceName) {
        final StringBuilder result = new StringBuilder();
        if (nonNull(prefix) && !resourceName.startsWith(prefix)) {
            result.append(prefix);
        }
        result.append(resourceName);
        if (nonNull(suffix)) {
            result.append(suffix);
        }
        return result.toString();
    }

    @Override
    public void setCharset(final String charset) {
        this.charset = charset;
    }

    @Override
    public void setPrefix(final String prefix) {
        this.prefix = prefix;
    }

    @Override
    public void setSuffix(final String suffix) {
        this.suffix = suffix;
    }

    @Override
    public String resolveRelativePath(final String relativePath, final String anchorPath) {
        return PathUtils.resolveRelativePath(relativePath, anchorPath, File.separatorChar);
    }

    @Override
    public String createCacheKey(final String templateName) {
        return templateName;
    }

}


text:
<!DOCTYPE html>

    <title>Opa Tests for TooPage App</title>
    <meta http-equiv='X-UA-Compatible' content='IE=edge' />
    <meta charset="UTF-8">


text:
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.core.management import call_command

class Migration(DataMigration):

    def forwards(self, orm):
        "Write your forwards methods here."

        # Needs to be run in a separate migration to avoid borking MySQL.
        call_command("installwatson", verbosity=0)

    def backwards(self, orm):
        "Write your backwards methods here."

        call_command("uninstallwatson", verbosity=0)

    models = {
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'watson.searchentry': {
            'Meta': {'object_name': 'SearchEntry'},
            'content': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'engine_slug': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'meta_encoded': ('django.db.models.fields.TextField', [], {}),
            'object_id': ('django.db.models.fields.TextField', [], {}),
            'object_id_int': ('django.db.models.fields.IntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '1000'}),
            'url': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'blank': 'True'})
        }
    }

    complete_apps = ['watson']


text:
FROM ubuntu:14.04
MAINTAINER CenturyLinkLabs

#Install dependencies for Wetty
RUN apt-get -qqy update && \
 apt-get -qqy install git nodejs npm && \
 ln -s /usr/bin/nodejs /usr/bin/node

#Install Wetty and set password
RUN git clone https://github.com/krishnasrinivas/wetty
WORKDIR /wetty
RUN npm install && \
 apt-get install -y vim && \
 useradd -d /home/term -m -s /bin/bash term && \
 echo 'term:term' | chpasswd

#Install Deis CLI
ADD https://s3-us-west-2.amazonaws.com/opdemand/deis-deb-wheezy-0.9.0.tgz /
RUN tar zxf /deis-deb-wheezy-0.9.0.tgz && mv deis /bin/deis

EXPOSE 3000

ENTRYPOINT ["node"]
CMD ["app.js", "-p", "3000"]


text:
title: year 9 IT lesson 3
layout: post
author: sam.shepherd
source-id: 1mxnCaYx125XBMl7x7huNdY-QcoMMYMGXW6JDv-ap47E
published: true
---

    SPREADSHEETS 3

    25/9/17

    Starting point:
    I now have a decent bit of knowledge in spreadsheets.

    Target for this lesson?
    I want to get to know some of the more advanced features of spreadsheets.

    Did I reach my target?
    I have gained some knowledge and also learned how to use the 'vlookup' command to find and use data in a range on a different sheet.

    Lesson Review

    How did I learn? What strategies were effective?

    I think that i have made a good amount of progress but i also think that i could have made much more progress had i been more successful in my discount prices. I also learned by exploring what I could do but also trying to find the simplest ways to perform the action that I was instructed to do.

    What limited my learning?

    I could have done much much better if i had only done parts of my spreadsheets neater. Otherwise Not much limited my learning as I focused on what I needed to do. Sometimes I asked my partner for help but he guided me towards finding out the answer to my problem instead of just telling me the answer to it. (Brendan Frank)

    What will I change for next time?

    The only thing really holding me back that lesson was the fact that some parts of my spreadsheets did not work fully. On the other hand there were some parts that i was quite proud of, like my vLookup.

Spreadsheets Work


text:
package com.yanjinbin.designPattern.组合模式;

/**
 * @author 颜巾斌
 *         Created on 七月 02  tag :windows
 */
public class CompositeClient {
    public static void  main(String[] args){
        Company root = new ConcreteCompany();
        root.setName("北京总公司");
        root.add(new HRDepartment("总公司人力资源部"));
        root.add(new FinanceDepartment("总公司财务部"));
        Company shandongCom = new ConcreteCompany("山东分公司");
        shandongCom.add(new HRDepartment("山东分公司人力资源部"));
        shandongCom.add(new FinanceDepartment("山东分公司账务部"));
        Company zaozhuangCom = new ConcreteCompany("枣庄办事处");
        zaozhuangCom.add(new FinanceDepartment("枣庄办事处财务部"));
        zaozhuangCom.add(new HRDepartment("枣庄办事处人力资源部"));
        Company jinanCom = new ConcreteCompany("济南办事处");
        jinanCom.add(new FinanceDepartment("济南办事处财务部"));
        jinanCom.add(new HRDepartment("济南办事处人力资源部"));
        shandongCom.add(jinanCom);
        shandongCom.add(zaozhuangCom);
        Company huadongCom = new ConcreteCompany("上海华东分公司");
        huadongCom.add(new HRDepartment("上海华东分公司人力资源部"));
        huadongCom.add(new FinanceDepartment("上海华东分公司账务部"));
        Company hangzhouCom = new ConcreteCompany("杭州办事处");
        hangzhouCom.add(new FinanceDepartment("杭州办事处财务部"));
        hangzhouCom.add(new HRDepartment("杭州办事处人力资源部"));
        Company nanjingCom = new ConcreteCompany("南京办事处");
        nanjingCom.add(new FinanceDepartment("南京办事处财务部"));
        nanjingCom.add(new HRDepartment("南京办事处人力资源部"));
        huadongCom.add(hangzhouCom);
        huadongCom.add(nanjingCom);
        root.add(shandongCom);
        root.add(huadongCom);
        root.display(0);
    }
}


text:
import { EmptyPhrasebook } from './phrasebook'
import FEED_PHRASES from '../phrases/feed.json'

export class FeedPhrasebook extends EmptyPhrasebook {
  constructor() {
    super()
    this.basePhraseJson = FEED_PHRASES
  }
}


text:
package sd_test

import (
	"io"
	"testing"
	"time"

	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/sd"
	"github.com/go-kit/kit/sd/internal/instance"
)

func TestDefaultEndpointer(t *testing.T) {
	var (
		ca = make(closer)
		cb = make(closer)
		c  = map[string]io.Closer{"a": ca, "b": cb}
		f  = func(instance string) (endpoint.Endpoint, io.Closer, error) {
			return endpoint.Nop, c[instance], nil
		}
		instancer = &mockInstancer{instance.NewCache()}
	)
	// set initial state
	instancer.Update(sd.Event{Instances: []string{"a", "b"}})

	endpointer := sd.NewEndpointer(instancer, f, log.NewNopLogger(), sd.InvalidateOnError(time.Minute))

	var (
		endpoints []endpoint.Endpoint
		err       error
	)
	if !within(time.Second, func() bool {
		endpoints, err = endpointer.Endpoints()
		return err == nil && len(endpoints) == 2
	}) {
		t.Errorf("wanted 2 endpoints, got %d (%v)", len(endpoints), err)
	}

	instancer.Update(sd.Event{Instances: []string{}})

	select {
	case <-ca:
		t.Logf("endpoint a closed, good")
	case <-time.After(time.Millisecond):
		t.Errorf("didn't close the deleted instance in time")
	}

	select {
	case <-cb:
		t.Logf("endpoint b closed, good")
	case <-time.After(time.Millisecond):
		t.Errorf("didn't close the deleted instance in time")
	}

	if endpoints, err := endpointer.Endpoints(); err != nil {
		t.Errorf("unepected error %v", err)
	} else if want, have := 0, len(endpoints); want != have {
		t.Errorf("want %d, have %d", want, have)
	}

	endpointer.Close()

	instancer.Update(sd.Event{Instances: []string{"a"}})
	// TODO verify that on Close the endpointer fully disconnects from the instancer.
	// Unfortunately, because we use instance.Cache, this test cannot be in the sd package,
	// and therefore does not have access to the endpointer's private members.
}

type mockInstancer struct{ *instance.Cache }

type closer chan struct{}

func (c closer) Close() error { close(c); return nil }

func within(d time.Duration, f func() bool) bool {
	deadline := time.Now().Add(d)
	for time.Now().Before(deadline) {
		if f() {
			return true
		}
		time.Sleep(d / 10)
	}
	return false
}


text:
export default (iVXjs, iVXjsValidationSchema) => {
    "ngInject";
    let playerIdCues = {};
}


text:
UCLASS()
class ENGINE_API UInputVectorAxisDelegateBinding : public UInputAxisKeyDelegateBinding
{
	GENERATED_UCLASS_BODY()

	// Begin UInputDelegateBinding interface
	virtual void BindToInputComponent(UInputComponent* InputComponent) const override;
	// End UInputDelegateBinding interface
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iMotto.Data.Entities
{
    public class UpdateInfo
    {
        public string DeviceType { get; set; }

        public string DisplayVersion { get; set; }

        public int DigitVersion { get; set; }

        public DateTime PubDate { get; set; }

        public string PubDesc { get; set; }

        public string Url { get; set; }

        public bool ForceUpdate { get; set; }

    }
}


text:
package org.contikios.cooja.mspmote.interfaces;

import java.awt.*;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;

import org.contikios.cooja.*;
import org.contikios.cooja.interfaces.LED;
import org.contikios.cooja.mspmote.SkyMote;
import se.sics.mspsim.core.IOPort;
import se.sics.mspsim.core.IOUnit;
import se.sics.mspsim.core.PortListener;
import se.sics.mspsim.platform.sky.SkyNode;

/**
 * @author Fredrik Osterlind
 */
@ClassDescription("Sky LED")
public class SkyLED extends LED {
  private static Logger logger = Logger.getLogger(SkyLED.class);

  private SkyMote mspMote;
  private boolean blueOn = false;
  private boolean greenOn = false;
  private boolean redOn = false;

  private static final Color DARK_BLUE = new Color(0, 0, 100);
  private static final Color DARK_GREEN = new Color(0, 100, 0);
  private static final Color DARK_RED = new Color(100, 0, 0);
  private static final Color BLUE = new Color(0, 0, 255);
  private static final Color GREEN = new Color(0, 255, 0);
  private static final Color RED = new Color(255, 0, 0);

  public SkyLED(Mote mote) {
    mspMote = (SkyMote) mote;

    IOUnit unit = mspMote.getCPU().getIOUnit("Port 5");
    if (unit instanceof IOPort) {
      ((IOPort) unit).addPortListener(new PortListener() {
        public void portWrite(IOPort source, int data) {
          blueOn = (data & SkyNode.BLUE_LED) == 0;
          greenOn = (data & SkyNode.GREEN_LED) == 0;
          redOn = (data & SkyNode.RED_LED) == 0;
          setChanged();
          notifyObservers();
        }
      });
    }
  }

  public boolean isAnyOn() {
    return blueOn || greenOn || redOn;
  }

  public boolean isGreenOn() {
    return greenOn;
  }

  public boolean isYellowOn()  {
    return blueOn; /* Returning blue */
  }

  public boolean isRedOn() {
    return redOn;
  }

  public JPanel getInterfaceVisualizer() {
    final JPanel panel = new JPanel() {
      public void paintComponent(Graphics g) {
        super.paintComponent(g);

        int x = 20;
        int y = 25;
        int d = 25;

        if (isGreenOn()) {
          g.setColor(GREEN);
          g.fillOval(x, y, d, d);
          g.setColor(Color.BLACK);
          g.drawOval(x, y, d, d);
        } else {
          g.setColor(DARK_GREEN);
          g.fillOval(x + 5, y + 5, d-10, d-10);
        }

        x += 40;

        if (isRedOn()) {
          g.setColor(RED);
          g.fillOval(x, y, d, d);
          g.setColor(Color.BLACK);
          g.drawOval(x, y, d, d);
        } else {
          g.setColor(DARK_RED);
          g.fillOval(x + 5, y + 5, d-10, d-10);
        }

        x += 40;

        if (isYellowOn()) {
          g.setColor(BLUE);
          g.fillOval(x, y, d, d);
          g.setColor(Color.BLACK);
          g.drawOval(x, y, d, d);
        } else {
          g.setColor(DARK_BLUE);
          g.fillOval(x + 5, y + 5, d-10, d-10);
        }
      }
    };

    Observer observer;
    this.addObserver(observer = new Observer() {
      public void update(Observable obs, Object obj) {
        panel.repaint();
      }
    });

    // Saving observer reference for releaseInterfaceVisualizer
    panel.putClientProperty("intf_obs", observer);

    panel.setMinimumSize(new Dimension(140, 60));
    panel.setPreferredSize(new Dimension(140, 60));

    return panel;
  }

  public void releaseInterfaceVisualizer(JPanel panel) {
    Observer observer = (Observer) panel.getClientProperty("intf_obs");
    if (observer == null) {
      logger.fatal("Error when releasing panel, observer is null");
      return;
    }

    this.deleteObserver(observer);
  }

  public Collection<Element> getConfigXML() {
    return null;
  }

  public void setConfigXML(Collection<Element> configXML, boolean visAvailable) {
  }

}


text:
package fathom.rest.controller;

import fathom.rest.controller.extractors.ExtractWith;
import fathom.rest.controller.extractors.IntExtractor;
import fathom.rest.controller.extractors.LongExtractor;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author James Moger
 */
@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@ExtractWith(LongExtractor.class)
public @interface Long {
    String value() default "";
    long defaultValue() default 0;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">


text:
/*
*/
#include"runsystems.hpp"
#include"phandles.hpp"

#include<boost/shared_ptr.hpp>
#include<queue>

/*single worker thread implementation*/

/*
Probably use *unofficial* boost::thread::threadpool on
http://threadpool.sourceforge.net/ for multiple
worker threads
*/

class SingleWorkerRunsystem : public Runsystem {
private:
	std::queue<boost::shared_ptr<ProcessHandle> > Q;
public:
	virtual void schedule(boost::shared_ptr<ProcessHandle> const& s){
		Q.push(s);
	}
	virtual void run(void){
		while(!Q.empty()){
			ProcessHandle& hproc = *Q.front();
			hproc();
			Q.pop();
		}
	}
	virtual bool singleprocess(void) const {
		return Q.size() == 1;
	}
	virtual ~SingleWorkerRunsystem(){}
};

Runsystem* NewRunsystem(void){
	return new SingleWorkerRunsystem();
}


text:
function showMessage($div, message, millis, done) {
  $div.text(message).fadeIn();
  if (millis > 0) {
    setTimeout(function() {
      $div.fadeOut('slow', done);
    }, millis);
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 <title>django-tinymce - Google Code</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

 <link rel="shortcut icon" href="http://code.google.com/favicon.ico"/>
 <link type="text/css" rel="stylesheet"
       href="_static/custom.css" />
 <link type="text/css" rel="stylesheet"
       href="http://www.gstatic.com/codesite/ph/4770211810525696068/css/d_20081117.css" />
 <link rel="stylesheet"  type="text/css"
       href="_static/pygments.css" />

 <link type="application/atom+xml" rel="alternate"
 href="/feeds/p/django-tinymce/svnchanges/basic?path=/wiki/" />

    <link rel="contents" title="Global table of contents" href="contents.html" />
    <link rel="index" title="Global index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="top" title="django-tinymce 2.0 documentation" href="index.html" />
    <link rel="next" title="Usage" href="usage.html" />
    <link rel="prev" title="Welcome to the django-tinymce documentation" href="index.html" />

 django-tinymce

 django-tinymce 2.0 documentation

 <form action="http://code.google.com/hosting/search">
 <input size=30 name=q value=""/>
 <input type=submit name=projectsearch value="Search Projects" />
 <input type=submit name=websearch value="Search the Web" />
 </form>

 Project Home

 Downloads

 Issues

 Source

 django-tinymce 2.0 documentation |

   next
  |

   previous
  |

   Search
    <form action="search.html" method="GET" style="display:inline">
      <input size=30 name=q value=""/>
      <input type=submit name=projectsearch value="Search Documentation" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Previous:

   Welcome to the django-tinymce documentation

Next:

   Usage

  Table of Contents

Installation

Prerequisites

Installation

Testing

Configuration

Installation¶

This section describes how to install the django-tinymce application in your Django
project.

Prerequisites¶

The django-tinymce application requires Django version 1.0 or higher. You will also
need TinyMCE version 3.0.1 or higher and a language pack for every
language you enabled in settings.LANGUAGES. If you use the django-filebrowser
application in your project, the tinymce application can use it as a browser
when including media.

If you want to use the spellchecker plugin using the supplied view (no PHP
needed) you must install the PyEnchant package and dictionaries for your
project languages. Note that the Enchant needs a dictionary that exactly
matches your language codes. For example, a dictionary for code 'en-us'
will not automatically be used for 'en'. You can check the availability of
the Enchant dictionary for the 'en' language code using the following
Python code:

import enchant
enchant.dict_exists('en')

Note that the documentation will use ‘TinyMCE’ (capitalized) to refer the
editor itself and ‘django-tinymce’ (lower case) to refer to the Django application.

Installation¶

Install django-tinymce using pip (or any other way to install python package) from PyPI. If you need to use a different way to install django-tinymce you can place the tinymce module on your Python path. You can put it into your Django project directory or run python setup.py install from a shell.

pip install django-tinymce

Add tinymce to INSTALLED_APPS in settings.py for your project:

INSTALLED_APPS = (
    ...
    'tinymce',
    ...
)

Add tinymce.urls to urls.py for your project:

urlpatterns = patterns('',
    ...
    (r'^tinymce/', include('tinymce.urls')),
    ...
)

Testing¶

Verify that everything is installed and configured properly:

Setup an isolated environment with virtualenv and activate environment:

virtualenv --no-site-packages env
. env/bin/activate

Install required packages:

pip install Django django-tinymce

Setup environment variable DJANGO_SETTINGS_MODULE:

export DJANGO_SETTINGS_MODULE='testtinymce.settings'

Setup test database (it will be created in current folder):

django-admin syncdb

Run Django runserver command to verify results:

django-admin runserver

Open this address in a browser:

http://localhost:8000/admin/testapp/testpage/add/

If you see TinyMCE instead of standard textarea boxes everything is working fine, otherwise check installation steps.

Configuration¶

The application can be configured by editing the project’s settings.py
file.

TINYMCE_JS_URL (default: settings.MEDIA_URL + 'js/tiny_mce/tiny_mce.js')

The URL of the TinyMCE javascript file:

TINYMCE_JS_URL = os.path.join(MEDIA_URL, "path/to/tiny_mce/tiny_mce.js")

TINYMCE_JS_ROOT (default: settings.MEDIA_ROOT + 'js/tiny_mce')

The filesystem location of the TinyMCE files. It is used by the compressor
(see below):

TINYMCE_JS_ROOT = os.path.join(MEDIA_ROOT, "path/to/tiny_mce")

TINYMCE_DEFAULT_CONFIG (default: {'theme': "simple", 'relative_urls': False})

The default TinyMCE configuration to use. See the TinyMCE manual for all
options. To set the configuration for a specific TinyMCE editor, see the
mce_attrs parameter for the widget.

TINYMCE_SPELLCHECKER (default: False)

Whether to use the spell checker through the supplied view. You must add
spellchecker to the TinyMCE plugin list yourself, it is not added
automatically.

TINYMCE_COMPRESSOR (default: False)

Whether to use the TinyMCE compressor, which gzips all Javascript files into
a single stream.  This makes the overall download size 75% smaller and also
reduces the number of requests. The overall initialization time for TinyMCE
will be reduced dramatically if you use this option.

TINYMCE_FILEBROWSER (default: True if 'filebrowser' is in INSTALLED_APPS, else False)

Whether to use the django-filebrowser as a custom filebrowser for media inclusion.
See the official TinyMCE documentation on custom filebrowsers.

Example:

TINYMCE_JS_URL = 'http://debug.example.org/tiny_mce/tiny_mce_src.js'
TINYMCE_DEFAULT_CONFIG = {
    'plugins': "table,spellchecker,paste,searchreplace",
    'theme': "advanced",
    'cleanup_on_startup': True,
    'custom_undo_redo_levels': 10,
}
TINYMCE_SPELLCHECKER = True
TINYMCE_COMPRESSOR = True

 ©2008 Google -
 Code Home -
 Terms of Service -
 Privacy Policy -