Inheritance: IExpVisitor
Ejemplo n.º 1
0
        public override void Emit(CodeGen cg)
        {
            bool eoiused = false;
            Label eoi = cg.DefineLabel();
            foreach (IfStatementTest t in _tests) {
                Label next = cg.DefineLabel();

                if (t.Test.Span.IsValid)
                {
                  cg.EmitPosition(t.Test.Start, t.Test.End);
                }

                t.Test.EmitBranchFalse(cg, next);

                t.Body.Emit(cg);

                // optimize no else case
                if (IsNotIfOrReturn(t.Body))
                {
                  eoiused = true;
                  cg.Emit(OpCodes.Br, eoi);
                }
                cg.MarkLabel(next);
            }
            if (_else != null) {
                _else.Emit(cg);
            }
            if (eoiused)
            {
              cg.MarkLabel(eoi);
            }
        }
Ejemplo n.º 2
0
 public void FixReturn(CodeGen cg)
 {
     _argSlot.EmitGet(cg);
     _refSlot.EmitGet(cg);
     cg.EmitCall(typeof(BinderOps).GetMethod("GetBox").MakeGenericMethod(_argSlot.Type.GetElementType()));
     cg.EmitStoreValueIndirect(_argSlot.Type.GetElementType());
 }
Ejemplo n.º 3
0
 internal override void EmitGet(CodeGen g)
 {
     Operand before = g.Local(target);
     baseOp.SetOperand(before);
     target.EmitSet(g, baseOp, false);
     before.EmitGet(g);
 }
Ejemplo n.º 4
0
		public IEnumerable<Instruction> EmitDerivation(MethodDef method, ConfuserContext ctx, Local dst, Local src) {
			var ret = new List<Instruction>();
			var codeGen = new CodeGen(dst, src, method, ret);
			codeGen.GenerateCIL(derivation);
			codeGen.Commit(method.Body);
			return ret;
		}
Ejemplo n.º 5
0
 public override void Emit(CodeGen cg)
 {
     if (_statement != null)
       {
     _statement.Emit(cg);
       }
 }
Ejemplo n.º 6
0
 public override void Emit(CodeGen cg)
 {
     //cg.EmitPosition(Start, End);
     // expression needs to be emitted incase it has side-effects.
     var ex = Expression.Unwrap(_expression);
     ex.EmitAs(cg, typeof(void));
 }
Ejemplo n.º 7
0
        public override void Emit(CodeGen cg) {
          if (_valueTypeType != null)
          {
            EmitLocation(cg);
            cg.EmitMissingValue(_valueTypeType); // seems ok?
          }
          else
          {
            for (int i = 0; i < _parameterInfos.Length; i++)
            {
              _arguments[i].Emit(cg);
              if (_arguments[i].Type != _parameterInfos[i].ParameterType && _arguments[i].Type.IsValueType && typeof(SymbolId) != _arguments[i].Type)
              {
                cg.EmitBoxing(_arguments[i].Type);
              }

            }
            EmitLocation(cg);
            cg.EmitNew(_constructor);
          }
          if (ScriptDomainManager.Options.LightweightDebugging && Span.IsValid)
          {
            cg.EmitConstant(SpanToLong(Span));
            cg.EmitCall(Debugging.DebugMethods.ExpressionOut);
          }
        }
		internal override void EmitGet(CodeGen g)
		{
			int[] bits = decimal.GetBits(value);
			byte exponent = unchecked((byte)((bits[3] >> 16) & 0x1f));
			bool sign = bits[3] < 0;

			if (exponent == 0 && bits[2] == 0)
			{
				if (bits[1] == 0 && (bits[0] > 0 || (bits[0] == 0 && !sign)))	// fits in int32 - use the basic int constructor
				{
					g.EmitI4Helper(sign ? -bits[0] : bits[0]);
					g.IL.Emit(OpCodes.Newobj, decimalIntConstructor);
					return;
				}
				if (bits[1] > 0)	// fits in int64
				{
					long l = unchecked((long)(((ulong)(uint)bits[1] << 32) | (ulong)(uint)bits[0]));
					g.IL.Emit(OpCodes.Ldc_I8, sign ? -l : l);
					g.IL.Emit(OpCodes.Newobj, decimalLongConstructor);
					return;
				}
			}

			g.EmitI4Helper(bits[0]);
			g.EmitI4Helper(bits[1]);
			g.EmitI4Helper(bits[2]);
			g.EmitI4Helper(sign ? 1 : 0);
			g.EmitI4Helper(exponent);
			g.IL.Emit(OpCodes.Newobj, decimalExtConstructor);
		}
Ejemplo n.º 9
0
        public override void Emit(CodeGen cg) {
          
            if (_typeOperand.IsAssignableFrom(_expression.Type)) {
                // if its always true just emit the bool
                cg.EmitConstant(true);
                return;
            }

            _expression.EmitAsObject(cg);

            EmitLocation(cg);

            cg.Emit(OpCodes.Isinst, _typeOperand);
            cg.Emit(OpCodes.Ldnull);
            cg.Emit(OpCodes.Cgt_Un);

            if (ScriptDomainManager.Options.LightweightDebugging)
            {
              if (!cg.IsDynamicMethod)
              {
                var s = SpanToLong(Span);
                cg.EmitConstant(s);
                cg.EmitCall(Debugging.DebugMethods.ExpressionOut);
              }
            }
        }
Ejemplo n.º 10
0
        public override void Emit(CodeGen cg)
        {
            if (Span.IsValid)
            {
              cg.EmitPosition(Start, End);

              if (ScriptDomainManager.Options.LightweightDebugging)
              {
                if (!cg.IsDynamicMethod)
                {
                  var s = SpanToLong(Span);
                  cg.EmitConstant(s);
                  cg.EmitCall(Debugging.DebugMethods.ExpressionInTail); // not really but will do for LW debugger
                }
              }
            }

            if (_statement != null) {
                cg.CheckAndPushTargets(_statement);
            }

            cg.EmitContinue();

            if (_statement != null) {
                cg.PopTargets();
            }
        }
		internal override void EmitGet(CodeGen g)
		{
			op.EmitGet(g);

			foreach (OpCode oc in opCodes)
				g.IL.Emit(oc);
		}
Ejemplo n.º 12
0
 public override void Emit(CodeGen cg) {
     // RuntimeHelpers.LookupName(CodeContext, name)
     cg.EmitCodeContext();
     cg.EmitSymbolId(_name);
     cg.EmitUnbox(typeof(SymbolId));
     cg.EmitCall(typeof(RuntimeHelpers), "LookupName");
 }
Ejemplo n.º 13
0
        public override void Emit(CodeGen cg) {
            // emit "this", if any
            EmitInstance(cg);

            if (ScriptDomainManager.Options.LightweightDebugging && Span.IsValid)
            {
              cg.EmitConstant(SpanToLong(Span));
              cg.EmitCall(Debugging.DebugMethods.ExpressionIn);
            }

            EmitLocation(cg);

            switch (_member.MemberType) {
                case MemberTypes.Field:
                    FieldInfo field = (FieldInfo)_member;
                    cg.EmitFieldGet(field);
                    break;                    
                case MemberTypes.Property:
                    PropertyInfo property = (PropertyInfo)_member;
                    cg.EmitPropertyGet(property);
                    break;
                default:
                    Debug.Assert(false, "Invalid member type");
                    break;
            }

            if (ScriptDomainManager.Options.LightweightDebugging && Span.IsValid)
            {
              cg.EmitConstant(SpanToLong(Span));
              cg.EmitCall(Debugging.DebugMethods.ExpressionOut);
            }
        }
Ejemplo n.º 14
0
        public override bool Execute()
        {
            var codegen = new CodeGen();
            if (SchemaFiles != null)
            {
                foreach (var schemaFile in SchemaFiles)
                {
                    var schema = Schema.Parse(System.IO.File.ReadAllText(schemaFile.ItemSpec));
                    codegen.AddSchema(schema);
                }
            }
            if (ProtocolFiles != null)
            {
                foreach (var protocolFile in ProtocolFiles)
                {
                    var protocol = Protocol.Parse(System.IO.File.ReadAllText(protocolFile.ItemSpec));
                    codegen.AddProtocol(protocol);
                }
            }

            var generateCode = codegen.GenerateCode();
            var namespaces = generateCode.Namespaces;
            for (var i = namespaces.Count - 1; i >= 0; i--)
            {
                var types = namespaces[i].Types;
                for (var j = types.Count - 1; j >= 0; j--)
                {
                    Log.LogMessage("Generating {0}.{1}", namespaces[i].Name, types[j].Name);
                }
            }

            codegen.WriteTypes(OutDir.ItemSpec);
            return true;
        }
Ejemplo n.º 15
0
 internal Label EnsureLabel(CodeGen cg) {
     if (!_initialized) {
         _label = cg.DefineLabel();
         _initialized = true;
     }
     return _label;
 }
Ejemplo n.º 16
0
 private void button2_Click(object sender, EventArgs e)
 {
     label2.ForeColor = Color.Cyan;
     label2.Text = "Being Compiled.";
     try
     {
         Scanner scanner = null;
         using (TextReader input = File.OpenText(openFileDialog1.FileName))
         {
             scanner = new Scanner(input);
         }
         Parser parser = new Parser(scanner.Tokens);
         CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(openFileDialog1.FileName) + ".exe");
         label2.ForeColor = Color.Lime;
         label2.Text = "Compiled! Check the directory this program is in, or click 'Test File' and check the console.";
         button3.Enabled = true;
     }
     catch (Exception ex)
     {
         textBox3.Show();
         textBox3.Text = ex.Message;
         label2.ForeColor = Color.Red;
         label2.Text = "Error!";
         button3.Enabled = false;
     }
 }
        private static Type GetEnvironmentType(int size, CodeGen cg, out ConstructorInfo ctor, out EnvironmentFactory ef)
        {
            Type envType;

            #region Generated partial factories

            // *** BEGIN GENERATED CODE ***

            if (size <= 32 && Options.OptimizeEnvironments) {
                if (size <= 2) {
                    envType = typeof(FunctionEnvironment2Dictionary);
                } else if (size <= 4) {
                    envType = typeof(FunctionEnvironment4Dictionary);
                } else if (size <= 8) {
                    envType = typeof(FunctionEnvironment8Dictionary);
                } else if (size <= 16) {
                    envType = typeof(FunctionEnvironment16Dictionary);
                } else {
                    envType = typeof(FunctionEnvironment32Dictionary);
                }
                ctor = envType.GetConstructor(new Type[] { typeof(FunctionEnvironmentDictionary), typeof(IModuleEnvironment), typeof(SymbolId[]), typeof(SymbolId[]) });
                ef = new FieldEnvironmentFactory(envType);
            } else {
                cg.EmitInt(size);
                envType = typeof(FunctionEnvironmentNDictionary);
                ctor = envType.GetConstructor(new Type[] { typeof(int), typeof(FunctionEnvironmentDictionary), typeof(IModuleEnvironment), typeof(SymbolId[]), typeof(SymbolId[]) });
                ef = new IndexEnvironmentFactory(size);
            }

            // *** END GENERATED CODE ***

            #endregion

            return envType;
        }
Ejemplo n.º 18
0
 public override void Emit(CodeGen cg)
 {
     // RuntimeHelpers.RemoveName(CodeContext, name)
     cg.EmitCodeContext();
     cg.EmitSymbolId(_name);
     cg.EmitCall(typeof(RuntimeHelpers), "RemoveName");
 }
Ejemplo n.º 19
0
 public override void EmitGet(CodeGen cg)
 {
     // RuntimeHelpers.LookupName(context, name)
     _frame.EmitGet(cg);
     cg.EmitSymbolId(_name);
     cg.EmitCall(typeof(RuntimeHelpers), "LookupName");
 }
Ejemplo n.º 20
0
 public override void Emit(CodeGen cg) {
   //EmitLocation(cg);
     _value.EmitAsObject(cg);
     cg.EmitCodeContext();
     cg.EmitSymbolId(_name);
     cg.EmitCall(typeof(RuntimeHelpers), "SetNameReorder");
 }
Ejemplo n.º 21
0
		protected internal override void EmitGet(CodeGen g)  
        {
		    OperandExtensions.SetLeakedState(this, false); 
			int[] bits = decimal.GetBits(_value);
			byte exponent = unchecked((byte)((bits[3] >> 16) & 0x1f));
			bool sign = bits[3] < 0;

		    Type intType = g.TypeMapper.MapType(typeof(int));
		    if (exponent == 0 && bits[2] == 0)
			{
				if (bits[1] == 0 && (bits[0] > 0 || (bits[0] == 0 && !sign)))	// fits in int32 - use the basic int constructor
				{
					g.EmitI4Helper(sign ? -bits[0] : bits[0]);
					g.IL.Emit(OpCodes.Newobj, (ConstructorInfo)g.TypeMapper.MapType(typeof(decimal)).GetConstructor(new Type[] { intType }));
					return;
				}
				if (bits[1] > 0)	// fits in int64
				{
					long l = unchecked((long)(((ulong)(uint)bits[1] << 32) | (ulong)(uint)bits[0]));
					g.IL.Emit(OpCodes.Ldc_I8, sign ? -l : l);
					g.IL.Emit(OpCodes.Newobj, (ConstructorInfo)g.TypeMapper.MapType(typeof(decimal)).GetConstructor(new Type[] { g.TypeMapper.MapType(typeof(long)) }));
					return;
				}
			}

			g.EmitI4Helper(bits[0]);
			g.EmitI4Helper(bits[1]);
			g.EmitI4Helper(bits[2]);
			g.EmitI4Helper(sign ? 1 : 0);
			g.EmitI4Helper(exponent);
			g.IL.Emit(OpCodes.Newobj, (ConstructorInfo)g.TypeMapper.MapType(typeof(decimal)).GetConstructor(
                new Type[] { intType, intType, intType, g.TypeMapper.MapType(typeof(bool)), g.TypeMapper.MapType(typeof(byte)) }));
		}
		void LoadArrayAndIndexes(CodeGen g)
		{
			array.EmitGet(g);

			foreach (Operand op in indexes)
				g.EmitGetHelper(op, Operand.GetType(op) == typeof(int) ? typeof(int) : typeof(long), false);
		}
Ejemplo n.º 23
0
		protected internal override void EmitGet(CodeGen g)  
        {
		    OperandExtensions.SetLeakedState(this, false); 
			Operand before = g.Local(_target);
			_baseOp.SetOperand(before);
			_target.EmitSet(g, _baseOp, false);
			before.EmitGet(g);
		}
Ejemplo n.º 24
0
        public override void EmitGetAddr(CodeGen cg)
        {
            Contract.RequiresNotNull(cg, "cg");

            Debug.Assert(cg == _codeGen);

            cg.Emit(OpCodes.Ldloca, _localBuilder);
        }
Ejemplo n.º 25
0
 internal override void EmitAddress(CodeGen cg, Type asType) {
     if (asType != Type || _member.MemberType != MemberTypes.Field) {
         base.EmitAddress(cg, asType);
     } else {
         EmitInstance(cg);
         cg.EmitFieldAddress((FieldInfo)_member);
     }
 }
Ejemplo n.º 26
0
        public override void EmitGet(CodeGen cg)
        {
            Contract.RequiresNotNull(cg, "cg");

            _param.EmitGet(cg);
            cg.EmitInt(_index);
            cg.Emit(OpCodes.Ldelem_Ref);
        }
Ejemplo n.º 27
0
 public override void EmitBranchFalse(CodeGen cg, Label label) {
     if (_valueIndex == _expressions.Count - 1) {
         Emit(cg, _valueIndex);
         _expressions[_valueIndex].EmitBranchFalse(cg, label);
     } else {
         base.EmitBranchFalse(cg, label);
     }
 }
Ejemplo n.º 28
0
		protected internal override void EmitGet(CodeGen g)  
        {
		    OperandExtensions.SetLeakedState(this, false); 
			_op.EmitGet(g);

			foreach (OpCode oc in _opCodes)
				g.IL.Emit(oc);
		}
Ejemplo n.º 29
0
        public override void EmitGetAddr(CodeGen cg)
        {
            Contract.RequiresNotNull(cg, "cg");

            _instance.EmitGet(cg);
            cg.EmitInt(_index);
            cg.Emit(OpCodes.Ldelema, Type);
        }
Ejemplo n.º 30
0
        protected internal override void EmitGet(CodeGen g)
        {
            OperandExtensions.SetLeakedState(this, false);
            if (ReferenceEquals(_local, null))
                _local = g.Local(_internal);

            _local.EmitGet(g);
        }
Ejemplo n.º 31
0
 internal override void EmitGet(CodeGen g)
 {
     g.IL.Emit(OpCodes.Ldstr, _str);
 }
Ejemplo n.º 32
0
 public override void Emit(CodeGen cg)
 {
     CreateGlobalSlots(cg);
     body.Emit(cg);
 }
Ejemplo n.º 33
0
 public override void EmitStorage(CodeGen cg)
 {
     cg.EmitNew(StorageType.GetConstructor(ArrayUtils.EmptyTypes));
     //cg.Emit(OpCodes.Dup);
     //EmitNestedTupleInit(cg, StorageType);
 }
Ejemplo n.º 34
0
 internal override void EmitGet(CodeGen g)
 {
     ctor.EmitArgs(g, args);
     g.IL.Emit(OpCodes.Newobj, (ConstructorInfo)ctor.Method.Member);
 }
Ejemplo n.º 35
0
 public override EnvironmentSlot CreateEnvironmentSlot(CodeGen cg)
 {
     return(new ClassEnvironmentSlot(cg.GetNamedLocal(StorageType, "$environment"), StorageType));
 }
Ejemplo n.º 36
0
        // example based on the MSDN User-Defined Conversions Sample (structconversion.cs)
        public static void GenStructConversion(AssemblyGen ag)
        {
            TypeGen BinaryNumeral = ag.Struct("BinaryNumeral");
            {
                FieldGen value = BinaryNumeral.Private.Field(typeof(int), "value");

                CodeGen g = BinaryNumeral.Public.Constructor().Parameter(typeof(int), "value");
                {
                    g.Assign(value, g.Arg("value"));
                }

                g = BinaryNumeral.Public.ImplicitConversionFrom(typeof(int));
                {
                    g.Return(Exp.New(BinaryNumeral, g.Arg("value")));
                }

                g = BinaryNumeral.Public.ImplicitConversionTo(typeof(string));
                {
                    g.Return("Conversion not yet implemented");
                }

                g = BinaryNumeral.Public.ExplicitConversionTo(typeof(int), "binary");
                {
                    g.Return(g.Arg("binary").Field("value"));
                }
            }

            TypeGen RomanNumeral = ag.Struct("RomanNumeral");
            {
                FieldGen value = RomanNumeral.Private.Field(typeof(int), "value");

                CodeGen g = RomanNumeral.Public.Constructor().Parameter(typeof(int), "value");
                {
                    g.Assign(value, g.Arg("value"));
                }

                g = RomanNumeral.Public.ImplicitConversionFrom(typeof(int));
                {
                    g.Return(Exp.New(RomanNumeral, g.Arg("value")));
                }

                g = RomanNumeral.Public.ImplicitConversionFrom(BinaryNumeral, "binary");
                {
                    g.Return(Exp.New(RomanNumeral, g.Arg("binary").Cast(typeof(int))));
                }

                g = RomanNumeral.Public.ExplicitConversionTo(typeof(int), "roman");
                {
                    g.Return(g.Arg("roman").Field("value"));
                }

                g = RomanNumeral.Public.ImplicitConversionTo(typeof(string));
                {
                    g.Return("Conversion not yet implemented");
                }
            }

            TypeGen Test = ag.Class("Test");
            {
                CodeGen g = Test.Public.Static.Method(typeof(void), "Main");
                {
                    Operand roman = g.Local(RomanNumeral);
                    g.Assign(roman, 10);
                    Operand binary = g.Local(BinaryNumeral);
                    // Perform a conversion from a RomanNumeral to a
                    // BinaryNumeral:
                    g.Assign(binary, roman.Cast(typeof(int)).Cast(BinaryNumeral));
                    // Performs a conversion from a BinaryNumeral to a RomanNumeral.
                    // No cast is required:
                    g.Assign(roman, binary);
                    g.WriteLine(binary.Cast(typeof(int)));
                    g.WriteLine(binary);
                }
            }
        }
Ejemplo n.º 37
0
        // example based on the MSDN User-Defined Conversions Sample (conversion.cs)
        public static void GenConversion(AssemblyGen ag)
        {
            TypeGen RomanNumeral = ag.Struct("RomanNumeral");
            {
                FieldGen value = RomanNumeral.Private.Field(typeof(int), "value");

                CodeGen g = RomanNumeral.Public.Constructor().Parameter(typeof(int), "value");
                {
                    g.Assign(value, g.Arg("value"));
                }

                // Declare a conversion from an int to a RomanNumeral. Note the
                // the use of the operator keyword. This is a conversion
                // operator named RomanNumeral:
                g = RomanNumeral.Public.ImplicitConversionFrom(typeof(int));
                {
                    // Note that because RomanNumeral is declared as a struct,
                    // calling new on the struct merely calls the constructor
                    // rather than allocating an object on the heap:
                    g.Return(Exp.New(RomanNumeral, g.Arg("value")));
                }

                // Declare an explicit conversion from a RomanNumeral to an int:
                g = RomanNumeral.Public.ExplicitConversionTo(typeof(int), "roman");
                {
                    g.Return(g.Arg("roman").Field("value"));
                }

                // Declare an implicit conversion from a RomanNumeral to
                // a string:
                g = RomanNumeral.Public.ImplicitConversionTo(typeof(string));
                {
                    g.Return("Conversion not yet implemented");
                }
            }

            TypeGen Test = ag.Class("Test");
            {
                CodeGen g = Test.Public.Static.Method(typeof(void), "Main");
                {
                    Operand numeral = g.Local(RomanNumeral);

                    g.Assign(numeral, 10);

                    // Call the explicit conversion from numeral to int. Because it is
                    // an explicit conversion, a cast must be used:
                    g.WriteLine(numeral.Cast(typeof(int)));

                    // Call the implicit conversion to string. Because there is no
                    // cast, the implicit conversion to string is the only
                    // conversion that is considered:
                    g.WriteLine(numeral);

                    // Call the explicit conversion from numeral to int and
                    // then the explicit conversion from int to short:
                    Operand s = g.Local(numeral.Cast(typeof(short)));

                    g.WriteLine(s);
                }
            }
        }
Ejemplo n.º 38
0
 public void Emit(CodeGen g)
 {
     _target.EmitSet(g, _baseOp, false);
 }
Ejemplo n.º 39
0
        // Use homotopy method with newton's method to find a solution for F(x) = 0.
        private static List <Arrow> NSolve(List <Expression> F, List <Arrow> x0, double Epsilon, int MaxIterations)
        {
            int M = F.Count;
            int N = x0.Count;

            // Compute JxF, the Jacobian of F.
            List <Dictionary <Expression, Expression> > JxF = Jacobian(F, x0.Select(i => i.Left)).ToList();

            // Define a function to evaluate JxH(x), where H = F(x) - s*F(x0).
            CodeGen code = new CodeGen();

            ParamExpr _JxH = code.Decl <double[, ]>(Scope.Parameter, "JxH");
            ParamExpr _x0  = code.Decl <double[]>(Scope.Parameter, "x0");
            ParamExpr _s   = code.Decl <double>(Scope.Parameter, "s");

            // Load x_j from the input array and add them to the map.
            for (int j = 0; j < N; ++j)
            {
                code.DeclInit(x0[j].Left, LinqExpr.ArrayAccess(_x0, LinqExpr.Constant(j)));
            }

            LinqExpr error = code.Decl <double>("error");

            // Compile the expressions to assign JxH
            for (int i = 0; i < M; ++i)
            {
                LinqExpr _i = LinqExpr.Constant(i);
                for (int j = 0; j < N; ++j)
                {
                    code.Add(LinqExpr.Assign(
                                 LinqExpr.ArrayAccess(_JxH, _i, LinqExpr.Constant(j)),
                                 code.Compile(JxF[i][x0[j].Left])));
                }
                // e = F(x) - s*F(x0)
                LinqExpr e = code.DeclInit <double>("e", LinqExpr.Subtract(code.Compile(F[i]), LinqExpr.Multiply(LinqExpr.Constant((double)F[i].Evaluate(x0)), _s)));
                code.Add(LinqExpr.Assign(LinqExpr.ArrayAccess(_JxH, _i, LinqExpr.Constant(N)), e));
                // error += e * e
                code.Add(LinqExpr.AddAssign(error, LinqExpr.Multiply(e, e)));
            }

            // return error
            code.Return(error);

            Func <double[, ], double[], double, double> JxH = code.Build <Func <double[, ], double[], double, double> >().Compile();

            double[] x = new double[N];

            // Remember where we last succeeded/failed.
            double s0 = 0.0;
            double s1 = 1.0;

            do
            {
                try
                {
                    // H(F, s) = F - s*F0
                    NewtonsMethod(M, N, JxH, s0, x, Epsilon, MaxIterations);

                    // Success at this s!
                    s1 = s0;
                    for (int i = 0; i < N; ++i)
                    {
                        x0[i] = Arrow.New(x0[i].Left, x[i]);
                    }

                    // Go near the goal.
                    s0 = Lerp(s0, 0.0, 0.9);
                }
                catch (FailedToConvergeException)
                {
                    // Go near the last success.
                    s0 = Lerp(s0, s1, 0.9);

                    for (int i = 0; i < N; ++i)
                    {
                        x[i] = (double)x0[i].Right;
                    }
                }
            } while (s0 > 0.0 && s1 >= s0 + 1e-6);

            // Make sure the last solution is at F itself.
            if (s0 != 0.0)
            {
                NewtonsMethod(M, N, JxH, 0.0, x, Epsilon, MaxIterations);
                for (int i = 0; i < N; ++i)
                {
                    x0[i] = Arrow.New(x0[i].Left, x[i]);
                }
            }

            return(x0);
        }
Ejemplo n.º 40
0
 public override void EmitGet(CodeGen g)
 {
     g.IL.Emit(OpCodes.Ldstr, str);
 }
            /// <summary>
            /// Iterate over all loaded mods and emit new types
            /// </summary>
            protected void Awake()
            {
                // Generate overloaded PQSMod types
                AssemblyGen assembly = new AssemblyGen(Guid.NewGuid().ToString(),
                                                       new CompilerOptions {
                    OutputPath = Path.GetTempFileName()
                });

                List <Type> modTypes = GetModTypes();

                foreach (Type modType in modTypes)
                {
                    if (typeof(PQSMod).IsAssignableFrom(modType))
                    {
                        // Get the ModLoader type we want to extend
                        Type loaderType = modTypes.FirstOrDefault(t =>
                                                                  t.BaseType != null && t.BaseType.FullName != null &&
                                                                  t.BaseType.FullName.StartsWith("Kopernicus.Configuration.ModLoader.ModLoader") &&
                                                                  t.BaseType.GetGenericArguments()[0] == modType);
                        if (loaderType == null)
                        {
                            continue;
                        }

                        // Generate the Mod Type
                        TypeGen modGen = assembly.Public.Class($"{modType.Name}Regional", modType);
                        {
                            FieldGen multiplierMap  = modGen.Public.Field(typeof(MapSO), "multiplierMap");
                            FieldGen splitChannels  = modGen.Public.Field(typeof(Boolean), "splitChannels");
                            FieldGen multiplier     = modGen.Private.Field(typeof(Color), "multiplier");
                            FieldGen preBuildColor  = modGen.Private.Field(typeof(Color), "preBuildColor");
                            FieldGen preBuildHeight = modGen.Private.Field(typeof(Double), "preBuildHeight");

                            // OnVertexBuildHeight
                            CodeGen onVertexBuild = modGen.Public.Override.Method(typeof(void), "OnVertexBuild")
                                                    .Parameter(typeof(PQS.VertexBuildData), "data");
                            {
                                ContextualOperand data = onVertexBuild.Arg("data");
                                onVertexBuild.Assign(multiplier, onVertexBuild.Local(multiplierMap.Invoke(
                                                                                         "GetPixelColor", new TypeMapper(),
                                                                                         data.Field("u"), data.Field("v"))));
                                onVertexBuild.If(!splitChannels);
                                {
                                    onVertexBuild.Assign(multiplier.Field("a", new TypeMapper()),
                                                         multiplier.Field("r", new TypeMapper()));
                                }
                                onVertexBuild.End();
                                onVertexBuild.Assign(preBuildColor, data.Field("vertColor"));
                                onVertexBuild.Assign(preBuildHeight, data.Field("vertHeight"));
                                onVertexBuild.Invoke(onVertexBuild.Base(), "OnVertexBuild", data);
                                onVertexBuild.Assign(data.Field("vertColor"),
                                                     assembly.StaticFactory.Invoke(typeof(Color), "Lerp", preBuildColor,
                                                                                   data.Field("vertColor"), multiplier.Field("a", new TypeMapper())));
                                onVertexBuild.Assign(data.Field("vertHeight"),
                                                     assembly.StaticFactory.Invoke(typeof(UtilMath), "Lerp", preBuildHeight,
                                                                                   data.Field("vertHeight"), multiplier.Field("r", new TypeMapper())));
                            }

                            // OnVertexBuildHeight
                            CodeGen onVertexBuildHeight = modGen.Public.Override.Method(typeof(void), "OnVertexBuildHeight")
                                                          .Parameter(typeof(PQS.VertexBuildData), "data");
                            {
                                ContextualOperand data = onVertexBuildHeight.Arg("data");
                                onVertexBuildHeight.Assign(multiplier, onVertexBuildHeight.Local(multiplierMap.Invoke(
                                                                                                     "GetPixelColor", new TypeMapper(),
                                                                                                     data.Field("u"), data.Field("v"))));
                                onVertexBuildHeight.If(!splitChannels);
                                {
                                    onVertexBuildHeight.Assign(multiplier.Field("a", new TypeMapper()),
                                                               multiplier.Field("r", new TypeMapper()));
                                }
                                onVertexBuildHeight.End();
                                onVertexBuildHeight.Assign(preBuildColor, data.Field("vertColor"));
                                onVertexBuildHeight.Assign(preBuildHeight, data.Field("vertHeight"));
                                onVertexBuildHeight.Invoke(onVertexBuildHeight.Base(), "OnVertexBuildHeight", data);
                                onVertexBuildHeight.Assign(data.Field("vertColor"),
                                                           assembly.StaticFactory.Invoke(typeof(Color), "Lerp", preBuildColor,
                                                                                         data.Field("vertColor"), multiplier.Field("a", new TypeMapper())));
                                onVertexBuildHeight.Assign(data.Field("vertHeight"),
                                                           assembly.StaticFactory.Invoke(typeof(UtilMath), "Lerp", preBuildHeight,
                                                                                         data.Field("vertHeight"), multiplier.Field("r", new TypeMapper())));
                            }
                        }

                        // Generate the Loader Type
                        modGen.Complete();
                        Type    modLoader = typeof(ModLoader <>).MakeGenericType(modGen.GetCompletedType());
                        TypeGen loaderGen =
                            assembly.Public.Class($"{modType.Name.Replace("PQSMod_", "").Replace("PQS", "")}Regional",
                                                  modLoader).Attribute(typeof(RequireConfigType), Kopernicus.ConfigParser.Enumerations.ConfigType.Node);
                        {
                            PropertyGen multiplierMap = loaderGen.Public.Property(typeof(MapSOParserRGB <MapSO>), "multiplierMap")
                                                        .Attribute(typeof(ParserTarget), "multiplierMap");
                            {
                                CodeGen getter = multiplierMap.Getter();
                                {
                                    getter.Return(getter.Base().Property("Mod").Field("multiplierMap"));
                                }
                                CodeGen setter = multiplierMap.Setter();
                                {
                                    setter.Assign(setter.Base().Property("Mod").Field("multiplierMap"),
                                                  setter.PropertyValue());
                                }
                            }

                            PropertyGen splitChannels = loaderGen.Public.Property(typeof(NumericParser <Boolean>), "splitChannels")
                                                        .Attribute(typeof(ParserTarget), "splitChannels");
                            {
                                CodeGen getter = splitChannels.Getter();
                                {
                                    getter.Return(getter.Base().Property("Mod").Field("splitChannels"));
                                }
                                CodeGen setter = splitChannels.Setter();
                                {
                                    setter.Assign(setter.Base().Property("Mod").Field("splitChannels"),
                                                  setter.PropertyValue());
                                }
                            }

                            FieldGen loader = loaderGen.Public.Field(loaderType, "loader")
                                              .BeginAttribute(typeof(ParserTarget), "Mod").SetField("AllowMerge", true).End();

                            CodeGen create_PQS = loaderGen.Public.Override.Method(typeof(void), "Create")
                                                 .Parameter(typeof(PQS), "pqsVersion");
                            {
                                ContextualOperand pqsVersion = create_PQS.Arg("pqsVersion");
                                create_PQS.Invoke(create_PQS.Base(), "Create", pqsVersion);
                                create_PQS.Assign(loader, assembly.ExpressionFactory.New(loaderType));
                                create_PQS.Invoke(loader, "Create", create_PQS.Base().Property("Mod"), pqsVersion);
                            }
                            CodeGen create_Mod_PQS = loaderGen.Public.Override.Method(typeof(void), "Create")
                                                     .Parameter(modGen, "_mod")
                                                     .Parameter(typeof(PQS), "pqsVersion");
                            {
                                ContextualOperand _mod       = create_Mod_PQS.Arg("_mod");
                                ContextualOperand pqsVersion = create_Mod_PQS.Arg("pqsVersion");
                                create_Mod_PQS.Invoke(create_Mod_PQS.Base(), "Create", _mod, pqsVersion);
                                create_Mod_PQS.Assign(loader, assembly.ExpressionFactory.New(loaderType));
                                create_Mod_PQS.Invoke(loader, "Create", create_Mod_PQS.Base().Property("Mod"), pqsVersion);
                            }
                        }
                    }
                }
                assembly.Save();

                // Hacking into my own mod. Oh well.
                modTypes.AddRange(assembly.GetAssembly().GetTypes());
                typeof(Parser).GetField("_modTypes", BindingFlags.NonPublic | BindingFlags.Static)
                ?.SetValue(null, modTypes);
            }
Ejemplo n.º 42
0
 /// <summary>
 /// Generates the code for the expression, leaving it on
 /// the stack typed as object.
 /// </summary>
 /// <param name="cg">Where to emit the code.</param>
 public void EmitAsObject(CodeGen cg)
 {
     this.Emit(cg);  // emit as Type
     cg.EmitBoxing(Type);
 }
Ejemplo n.º 43
0
 /// <summary>
 /// This is the dual of EmitBranchFalse.
 /// </summary>
 public virtual void EmitBranchTrue(CodeGen cg, Label label)
 {
     this.EmitAs(cg, typeof(bool));
     cg.Emit(OpCodes.Brtrue, label);
 }
Ejemplo n.º 44
0
 public override void Emit(CodeGen cg)
 {
     cg.EmitConstant(_value);
 }
Ejemplo n.º 45
0
 protected void CreateClosureSlots(CodeGen cg)
 {
     CreateClosureSlots(cg.StaticLinkSlot, cg.Names);
 }
Ejemplo n.º 46
0
 public override void EmitGet(CodeGen g)
 {
     op.EmitGet(g);
     g.IL.Emit(OpCodes.Isinst, t);
 }
Ejemplo n.º 47
0
        protected Slot CreateEnvironment(CodeGen cg)
        {
            // Get the environment size
            int size = CalculateEnvironmentSize();

            // Create the array for the names
            Slot namesSlot = cg.GetLocalTmp(typeof(SymbolId[]));

            cg.EmitInt(size - tempsCount);
            cg.Emit(System.Reflection.Emit.OpCodes.Newarr, typeof(SymbolId));
            namesSlot.EmitSet(cg);

            // Find the right environment type
            ConstructorInfo    ctor;
            EnvironmentFactory esf;
            Type envType = GetEnvironmentType(size, cg, out ctor, out esf);

            // Emit the static link for the environment constructor
            cg.EmitStaticLinkOrNull();
            cg.EmitCallerContext();
            // Emit the names array for the environment constructor
            namesSlot.EmitGet(cg);
            cg.EmitNew(ctor);

            // Store the environment reference in the local
            Slot environmentSlot = cg.GetFrameSlot(envType);

            environmentSlot.EmitSet(cg);

            // Remember the environment factory for parent access
            environmentFactory = esf;

            // Create environment references
            environment = new Dictionary <Name, EnvironmentReference>();

            foreach (KeyValuePair <Name, Binding> kv in names)
            {
                if (!kv.Value.IsEnvironment)
                {
                    continue;
                }
                Name name = kv.Key;
                EnvironmentReference er = esf.MakeEnvironmentReference(name);
                Slot slot = er.CreateSlot(environmentSlot);
                Slot current;
                if (cg.Names.Slots.TryGetValue(name, out current))
                {
                    slot.EmitSet(cg, current);
                }
                else
                {
                    slot.EmitSetUninitialized(cg, name);
                }

                // Set the name into the array
                namesSlot.EmitGet(cg);
                cg.EmitInt(er.Index);
                cg.Emit(OpCodes.Ldelema, typeof(SymbolId));
                cg.EmitSymbolIdInt(name.GetString());
                cg.Emit(OpCodes.Call, typeof(SymbolId).GetConstructor(new Type[] { typeof(int) }));

                // The full slot goes to the codegen's namespace
                cg.Names.SetSlot(name, slot);
                // Environment reference goes to the environment
                environment[name] = er;
            }

            return(environmentSlot);
        }
Ejemplo n.º 48
0
 public override void EmitGetStorageFromContext(CodeGen cg)
 {
     cg.EmitCodeContext();
     cg.EmitPropertyGet(typeof(CodeContext), "Scope");
     cg.EmitCall(typeof(RuntimeHelpers).GetMethod("GetStorageData").MakeGenericMethod(StorageType));
 }
Ejemplo n.º 49
0
 internal override void EmitGet(CodeGen g)
 {
     g.EmitGetHelper(_target, g.TypeMapper.MapType(typeof(object)), false);
     g.IL.Emit(OpCodes.Ldftn, _method);
     g.IL.Emit(OpCodes.Newobj, _delegateConstructor);
 }
Ejemplo n.º 50
0
 public override void EmitStorage(CodeGen cg)
 {
     cg.EmitNew(StorageType.GetConstructor(ArrayUtils.EmptyTypes));
 }
        protected override IEnumerable <string> CommandLineFlagsForLibrary(PrecompiledLibrary library, CodeGen codegen)
        {
            // if lib which contains all JNI code is linked statically, then all methods from this lib should be exposed
            var entryPoint = library.ToString().Contains("lib_unity_tiny_android.a");

            if (entryPoint)
            {
                yield return("-Wl,--whole-archive");
            }
            foreach (var flag in base.CommandLineFlagsForLibrary(library, codegen))
            {
                yield return(flag);
            }
            if (entryPoint)
            {
                yield return("-Wl,--no-whole-archive");
            }
        }
Ejemplo n.º 52
0
 public void SetAppPackagingParameters(String gameName, CodeGen codeGen, IEnumerable <IDeployable> supportFiles)
 {
     m_gameName     = gameName.Replace(".", "-");
     m_codeGen      = codeGen;
     m_supportFiles = supportFiles;
 }
        public void LogWarning(RuntimeData.WarningID ID, string message, string filename, int line, int col)
        {
            filename = filename ?? string.Empty;

            if (!this.core.Options.IsDeltaExecution && (string.IsNullOrEmpty(filename) ||
                                                        line == Constants.kInvalidIndex ||
                                                        col == Constants.kInvalidIndex))
            {
                CodeGen.AuditCodeLocation(core, ref filename, ref line, ref col);
            }

            var warningMsg = string.Format(StringConstants.kConsoleWarningMessage,
                                           message, filename, line, col);

            if (core.Options.Verbose)
            {
                System.Console.WriteLine(warningMsg);
            }

            if (WebMessageHandler != null)
            {
                var outputMessage = new OutputMessage(warningMsg);
                WebMessageHandler.Write(outputMessage);
            }

            if (MessageHandler != null)
            {
                var outputMessage = new OutputMessage(OutputMessage.MessageType.Warning,
                                                      message.Trim(), filename, line, col);
                MessageHandler.Write(outputMessage);
            }

            AssociativeGraph.GraphNode executingGraphNode = null;
            var executive = core.CurrentExecutive.CurrentDSASMExec;

            if (executive != null)
            {
                executingGraphNode = executive.Properties.executingGraphNode;
                // In delta execution mode, it means the warning is from some
                // internal graph node.
                if (executingGraphNode != null && executingGraphNode.guid.Equals(System.Guid.Empty))
                {
                    executingGraphNode = core.ExecutingGraphnode;
                }
            }

            var entry = new RuntimeData.WarningEntry
            {
                ID            = ID,
                Message       = message,
                Column        = col,
                Line          = line,
                ExpressionID  = core.RuntimeExpressionUID,
                GraphNodeGuid = executingGraphNode == null ? Guid.Empty : executingGraphNode.guid,
                AstID         = executingGraphNode == null ? Constants.kInvalidIndex : executingGraphNode.OriginalAstID,
                Filename      = filename
            };

            warnings.Add(entry);

            if (core.Options.IsDeltaExecution)
            {
            }
        }
Ejemplo n.º 54
0
        protected override IEnumerable <string> CommandLineFlagsFor(NPath destination, CodeGen codegen, IEnumerable <NPath> objectFiles)
        {
            if (Toolchain.Architecture is ARMv7Architecture)
            {
                yield return("-arch_only");

                yield return("armv7");
            }

            if (Toolchain.Architecture is Arm64Architecture)
            {
                yield return("-arch_only");

                yield return("arm64");
            }

            yield return("-static");

            foreach (var objectFile in objectFiles)
            {
                yield return(objectFile.InQuotes());
            }

            yield return("-o");

            yield return(ChangeMainModuleName(destination).InQuotes());
        }
Ejemplo n.º 55
0
 public override void EmitGet(CodeGen g)
 {
     g.EmitGetHelper(target, typeof(object), false);
     g.IL.Emit(OpCodes.Ldftn, method);
     g.IL.Emit(OpCodes.Newobj, delegateConstructor);
 }
Ejemplo n.º 56
0
 protected override IEnumerable <string> CommandLineFlagsForLibrary(PrecompiledLibrary library, CodeGen codegen)
 {
     if (BundleStaticLibraryDependencies && library.Static)
     {
         yield return(library.InQuotes());
     }
 }
Ejemplo n.º 57
0
        public static void LoadAll()
        {
            string path = Settings.GetRunningDirectory() + "plugins" +
                          Path.DirectorySeparatorChar;

            log.Info("Plugin path: " + path);

            if (!Directory.Exists(path))
            {
                return;
            }

            // cs plugins are background compiled, and loaded in the ui thread
            Task.Run(() =>
            {
                String[] csFiles = Directory.GetFiles(path, "*.cs");

                foreach (var csFile in csFiles)
                {
                    log.Info("Plugin: " + csFile);
                    //Check if it is disabled (moved out from the previous IF, to make it loggable)
                    if (DisabledPluginNames.Contains(Path.GetFileName(csFile).ToLower()))
                    {
                        log.InfoFormat("Plugin {0} is disabled in config.xml", Path.GetFileName(csFile));
                        continue;
                    }

                    //loadassembly: MissionPlanner.WebAPIs
                    var content = File.ReadAllText(csFile);

                    var matches = Regex.Matches(content, @"^\/\/loadassembly: (.*)$", RegexOptions.Multiline);
                    foreach (Match m in matches)
                    {
                        try
                        {
                            log.Info("Try load " + m.Groups[1].Value.Trim());
                            Assembly.Load(m.Groups[1].Value.Trim());
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex);
                        }
                    }

                    try
                    {
                        // csharp 8
                        var ans = CodeGenRoslyn.BuildCode(csFile);

                        InitPlugin(ans, Path.GetFileName(csFile));

                        continue;
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex);
                    }


                    try
                    {
                        //csharp 5 max

                        // create a compiler
                        var compiler = CodeGen.CreateCompiler();
                        // get all the compiler parameters
                        var parms = CodeGen.CreateCompilerParameters();
                        // compile the code into an assembly
                        var results = CodeGen.CompileCodeFile(compiler, parms, csFile);

                        InitPlugin(results?.CompiledAssembly, Path.GetFileName(csFile));

                        if (results?.CompiledAssembly != null)
                        {
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex);
                    }
                }

                MainV2.instance.BeginInvokeIfRequired(() =>
                {
                    PluginInit();
                });
            });

            String[] files = Directory.GetFiles(path, "*.dll");
            foreach (var s in files)
            {
                Load(Path.Combine(Environment.CurrentDirectory, s));
            }

            InitPlugin(Assembly.GetAssembly(typeof(PluginLoader)), "self");

            PluginInit();
        }
Ejemplo n.º 58
0
 public override void Emit(CodeGen cg)
 {
     //cg.EmitPosition(Start, End);
     cg.EmitYield(_expr, _target);
 }
 public BuilderGen(CodeGen generator)
     : base(generator)
 {
 }
Ejemplo n.º 60
0
 /// <summary>
 /// Generates code for this expression in a value position.
 /// This method will leave the value of the expression
 /// on the top of the stack typed as Type.
 /// </summary>
 /// <param name="cg">Where to generate the code.</param>
 public abstract void Emit(CodeGen cg);