示例#1
0
		internal static int LoadChunk(Script script, SourceCode source, ByteCode bytecode, Table globalContext)
		{
			ScriptLoadingContext lcontext = CreateLoadingContext(script, source);
			try
			{
				Statement stat;

				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation))
					stat = new ChunkStatement(lcontext, globalContext);

				int beginIp = -1;

				//var srcref = new SourceRef(source.SourceID);

				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Compilation))
				using (bytecode.EnterSource(null))
				{
					bytecode.Emit_Nop(string.Format("Begin chunk {0}", source.Name));
					beginIp = bytecode.GetJumpPointForLastInstruction();
					stat.Compile(bytecode);
					bytecode.Emit_Nop(string.Format("End chunk {0}", source.Name));
				}

				//Debug_DumpByteCode(bytecode, source.SourceID);

				return beginIp;
			}
			catch (SyntaxErrorException ex)
			{
				ex.DecorateMessage(script);
				throw;
			}
		}
示例#2
0
		public void GetSigOpCount()
		{
			// Test CScript::GetSigOpCount()
			Script s1 = new Script();
			Assert.Equal(s1.GetSigOpCount(false), 0U);
			Assert.Equal(s1.GetSigOpCount(true), 0U);

			uint160 dummy = new uint160(0);
			s1 = s1 + OpcodeType.OP_1 + dummy.ToBytes() + dummy.ToBytes() + OpcodeType.OP_2 + OpcodeType.OP_CHECKMULTISIG;
			Assert.Equal(s1.GetSigOpCount(true), 2U);
			s1 = s1 + OpcodeType.OP_IF + OpcodeType.OP_CHECKSIG + OpcodeType.OP_ENDIF;
			Assert.Equal(s1.GetSigOpCount(true), 3U);
			Assert.Equal(s1.GetSigOpCount(false), 21U);

			Script p2sh = PayToScriptHashTemplate.Instance.GenerateScriptPubKey(s1);
			Script scriptSig = PayToScriptHashTemplate.Instance.GenerateScriptSig(new[] { (Op)OpcodeType.OP_0 }, s1);
			Assert.Equal(p2sh.GetSigOpCount(scriptSig), 3U);

			PubKey[] keys = Enumerable.Range(0, 3).Select(_ => new Key(true).PubKey).ToArray();

			Script s2 = PayToMultiSigTemplate.Instance.GenerateScriptPubKey(1, keys);
			Assert.Equal(s2.GetSigOpCount(true), 3U);
			Assert.Equal(s2.GetSigOpCount(false), 20U);

			p2sh = PayToScriptHashTemplate.Instance.GenerateScriptPubKey(s2);
			Assert.Equal(p2sh.GetSigOpCount(true), 0U);
			Assert.Equal(p2sh.GetSigOpCount(false), 0U);
			Script scriptSig2 = new Script();
			scriptSig2 = scriptSig2 + OpcodeType.OP_1 + dummy.ToBytes() + dummy.ToBytes() + s2.ToBytes();
			Assert.Equal(p2sh.GetSigOpCount(scriptSig2), 3U);
		}
示例#3
0
		private bool ReadScript(Script script)
		{
			try
			{
				var data = TxNullDataTemplate.Instance.ExtractScriptPubKeyParameters(script);
				if(data == null)
					return false;
				BitcoinStream stream = new BitcoinStream(data);
				ushort marker = 0;
				stream.ReadWrite(ref marker);
				if(marker != Tag)
					return false;
				stream.ReadWrite(ref _Version);
				if(_Version != 1)
					return false;

				ulong quantityCount = 0;
				stream.ReadWriteAsVarInt(ref quantityCount);
				Quantities = new ulong[quantityCount];

				for(ulong i = 0 ; i < quantityCount ; i++)
				{
					Quantities[i] = ReadLEB128(stream);
					if(Quantities[i] > MAX_QUANTITY)
						return false;
				}

				stream.ReadWriteAsVarString(ref _Metadata);
				return true;
			}
			catch(Exception)
			{
				return false;
			}
		}
 public override void Set(Script script, Scope scope, object obj, object value)
 {
     if (_isMethod)
     {
         throw new Exception("The left-hand side of an assignment must be a variable, property or indexer.");
     }
     else
     {
         Type t = obj.GetType();
         PropertyInfo result = t.GetProperty(_name);
         if (result != null)
         {
             if (!result.CanWrite)
             {
                 throw new FieldAccessException("Cannot modify the value of " + _name + ", it is read-only.");
             }
             result.GetSetMethod().Invoke(obj, new[] {value});
         }
         else
         {
             FieldInfo[] fi = t.GetFields();
             for (int i = 0; i < fi.Length; i++)
             {
                 if (fi[i].Name == _name)
                 {
                     fi[i].SetValue(obj, value);
                     return;
                 }
             }
         }
     }
 }
        public override object Execute(Script script, Scope scope, Token previousToken, object unknown)
        {
            if (unknown == null)
            {
                throw new NullReferenceException("obj cannot be null...");
            }

            if (unknown is object[])
            {
                // We are assuming that the tokens count is 1, and that it gives us a number.
                if (_tokens.Count == 1)
                {
                    // Evaluate.
                    object id = new Chunk(_tokens[0], script).Evaluate(scope);
                    if (id != null && id is Number)
                    {
                        return ((object[]) unknown)[((Number) id).GetValue<int>()];
                    }
                    else
                    {
                        throw new Exception("For a array of type object[], the key must be a number!");
                    }
                }
                throw new Exception(":O");
            }
            else
            {
                Type type = (unknown is Type) ? (Type) unknown : unknown.GetType();
                return Invoke(script, scope, unknown, type, (type == typeof(String)) ? "Chars" : "Item",
                              _tokens, new List<string>());
            }
        }
        public override object Execute(Script script, Scope scope, Token previousToken, object unknown)
        {
            if (unknown == null && previousToken != null)
            {
                // Cannot execute.
                throw new NullReferenceException("obj cannot be null...");
            }
            else if (unknown == null && previousToken == null)
            {
                // Check our list of "functions".
                if (scope.Functions.Contains(_name))
                {
                    return scope.Functions.Invoke(script, scope, _name, _arguments);
                }
                else if (script.Engine != null && script.Engine.Functions.Contains(_name))
                {
                    return script.Engine.Functions.Invoke(script, scope, _name, _arguments);
                }
                else
                {
                    throw new Exception(String.Format("No function named {0}...", _name));
                }
            }

            Type type = (unknown is Type) ? (Type) unknown : unknown.GetType();

            return _isMethod
                       ? Invoke(script, scope, unknown, type, _name, _arguments, _generics)
                       : FieldInvoke(unknown, _name, type);
        }
		void Do(string code, Action<DynValue, RegCollMethods> asserts)
		{
			try
			{
				UserData.RegisterType<RegCollMethods>();
				UserData.RegisterType<RegCollItem>();
				UserData.RegisterType(typeof(IList<>));

				Script s = new Script();

				var obj = new RegCollMethods();
				s.Globals["o"] = obj;
				s.Globals["ctor"] = UserData.CreateStatic<RegCollItem>();

				DynValue res = s.DoString(code);

				asserts(res, obj);
			}
			catch (ScriptRuntimeException ex)
			{
				Debug.WriteLine(ex.DecoratedMessage);
				throw;
			}
			finally
			{
				UserData.UnregisterType<RegCollMethods>();
				UserData.UnregisterType<RegCollItem>();
				UserData.UnregisterType<Array>();
				UserData.UnregisterType(typeof(IList<>));
				UserData.UnregisterType(typeof(IList<RegCollItem>));
				UserData.UnregisterType(typeof(IList<int>));
				//UserData.UnregisterType<IEnumerable>();
			}
		}
示例#8
0
		public void TailCallFromCLR()
		{
			string script = @"
				function getResult(x)
					return 156*x;  
				end

				return clrtail(9)";


			Script S = new Script();

			S.Globals.Set("clrtail", DynValue.NewCallback((xc, a) =>
			{
				DynValue fn = S.Globals.Get("getResult");
				DynValue k3 = DynValue.NewNumber(a[0].Number / 3);

				return DynValue.NewTailCallReq(fn, k3);
			}));

			var res = S.DoString(script);

			Assert.AreEqual(DataType.Number, res.Type);
			Assert.AreEqual(468, res.Number);
		}
示例#9
0
		internal static int LoadFunction(Script script, SourceCode source, ByteCode bytecode, Table globalContext)
		{
			ScriptLoadingContext lcontext = CreateLoadingContext(script, source);

			try
			{
				FunctionDefinitionExpression fnx;

				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation))
					fnx = new FunctionDefinitionExpression(lcontext, globalContext);

				int beginIp = -1;

				//var srcref = new SourceRef(source.SourceID);

				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Compilation))
				using (bytecode.EnterSource(null))
				{
					bytecode.Emit_Nop(string.Format("Begin function {0}", source.Name));
					beginIp = fnx.CompileBody(bytecode, source.Name);
					bytecode.Emit_Nop(string.Format("End function {0}", source.Name));
				}

				//Debug_DumpByteCode(bytecode, source.SourceID);

				return beginIp;
			}
			catch (SyntaxErrorException ex)
			{
				ex.DecorateMessage(script);
				throw;
			}

		}
		public override Script CombineScriptSig(Script scriptPubKey, Script a, Script b)
		{
			var para = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey);
			// Combine all the signatures we've got:
			var aSigs = PayToMultiSigTemplate.Instance.ExtractScriptSigParameters(a);
			if(aSigs == null)
				return b;
			var bSigs = PayToMultiSigTemplate.Instance.ExtractScriptSigParameters(b);
			if(bSigs == null)
				return a;
			int pubkeyCount = 0;
			TransactionSignature[] sigs = new TransactionSignature[para.PubKeys.Length];
			for(int i = 0 ; i < para.PubKeys.Length ; i++)
			{
				var aSig = i < aSigs.Length ? aSigs[i] : null;
				var bSig = i < bSigs.Length ? bSigs[i] : null;
				var sig = aSig ?? bSig;
				if(sig != null)
				{
					sigs[pubkeyCount] = sig; 
					pubkeyCount++;
				}
				if(pubkeyCount == para.SignatureCount)
					break;
			}
			if(pubkeyCount == para.SignatureCount)
				sigs = sigs.Where(s => s != null && s != TransactionSignature.Empty).ToArray();
			return PayToMultiSigTemplate.Instance.GenerateScriptSig(sigs);
		}		
示例#11
0
 public static void Load(Script script)
 {
     ScriptTable Table = script.CreateTable();
     Table.SetValue("encode", script.CreateFunction(new encode()));
     Table.SetValue("decode", script.CreateFunction(new decode(script)));
     script.SetObjectInternal("json", Table);
 }
        //////////////////////////////////////////////////////////////////////////
        public void LoadScript(DebugClient Client, Script Script)
        {
            _Client = Client;
            _Script = Script;

            this.BeginUpdate();
            this.Items.Clear();

            SourceValid = false;

            if (_Client != null && _Script != null)
            {
                string FullPath = _Client.Server.ResolveFilename(_Script.Filename);
                ReadLines(FullPath);
                SelectLine(Script.Line, true);
            }

            foreach (ColumnHeader Col in this.Columns)
            {
                Col.Width = -1;
            }
            this.EndUpdate();

            RefreshBreakpoints();
        }
        public override Token Build(Token lastToken, ScriptEngine engine, Script script, ref SourceCode sourceCode)
        {
            while ((++sourceCode).SpecialChar)
            {
            }
            if (sourceCode.Peek() != '{')
            {
                sourceCode.Throw(String.Format("Error parsing a 'do' statement, expected a '{' but got '{0}' instead.",
                                               sourceCode.Peek()));
            }
            List<List<List<Token>>> code = engine.BuildLongTokens(ref sourceCode, ref script, new[] {'}'});

            if (!sourceCode.SeekToNext("while"))
            {
                sourceCode.Throw("Error parsing a 'do' statement, was expecting a 'while' after the { } block.");
            }

            if (!sourceCode.SeekToNext('('))
            {
                sourceCode.Throw("Error parsing a 'do' statement, was expecting a '(' after 'while'.");
            }

            List<List<Token>> exitCondition = engine.BuildTokensAdvanced(ref sourceCode, ref script, new[] {')'});

            return new DoWhileToken(code, exitCondition);
        }
示例#14
0
		public void TableAddWithMetatable()
		{
			string script = @"    
				v1 = { 'aaaa' }
				v2 = { 'aaaaaa' } 

				meta = { }

				function meta.__add(t1, t2)
					local o1 = #t1[1];
					local o2 = #t2[1];
	
					return o1 * o2;
				end


				setmetatable(v1, meta);


				return(v1 + v2);";

			var S = new Script();
			Table globalCtx = S.Globals;

			globalCtx.RegisterModuleType<TableIteratorsModule>();
			globalCtx.RegisterModuleType<MetaTableModule>();

			DynValue res = S.DoString(script);

			Assert.AreEqual(DataType.Number, res.Type);
			Assert.AreEqual(24, res.Number);
		}
示例#15
0
        public override Token Build(Token lastToken, ScriptEngine engine, Script script, ref SourceCode sourceCode)
        {
            // while (condition) { /* Code */ }
            sourceCode += 4; // The +1 comes from below.

            while ((++sourceCode).SpecialChar)
            {
            }

            if (sourceCode.CurrentCode != '(')
            {
                sourceCode.Throw("Error parsing a 'while' statement, was epexting a '(' after 'while'.");
            }

            List<List<Token>> exitCondition = engine.BuildTokensAdvanced(ref sourceCode, ref script, new[] {')'});

            if (!sourceCode.SeekToNext('{'))
            {
                sourceCode.Throw(String.Format("Unexpected char: '{0}'", sourceCode.CurrentCode));
            }

            List<List<List<Token>>> code = engine.BuildLongTokens(ref sourceCode, ref script, new[] {'}'});

            return new WhileLoopToken(exitCondition, code);
        }
示例#16
0
        public DocumentTabForm(Script script)
        {
            if (script == null) throw new ArgumentNullException("script");

            Script = script;
            InitializeComponent();

            DockHandler = new DockContentHandler(this);
            DockHandler.DockAreas = DockAreas.Document;
            DockHandler.AllowEndUserDocking = false;

            Controls.Add(textEditor);

            textEditor.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
            textEditor.Name = "textEditor";
            textEditor.BorderStyle = BorderStyle.Fixed3D;
            textEditor.ShowMatchingBracket = true;
            textEditor.SetHighlighting("lua");
            textEditor.ShowSpaces = true;
            textEditor.ShowTabs = true;
            textEditor.Dock = DockStyle.Fill;
            textEditor.Text = Script.Text;

            script.NameChanged += ScriptNameChanged;
            FormClosed += (sender, args) => {
                script.NameChanged -= ScriptNameChanged;
            };
            Text = Script.ShortName;
        }
示例#17
0
		private static DynValue GetStandardFile(Script S, StandardFileType file)
		{
			Table R = S.Registry;

			DynValue ff = R.Get("853BEAAF298648839E2C99D005E1DF94_STD_" + file.ToString());
			return ff;
		}
示例#18
0
        /// <summary>
        /// Compiles a Script object to allow it to be Executed
        /// </summary>
        /// <param name="script">Script object to be compiled</param>
        public void Compile(Script script)
        {
            if (!compilerInfo.ContainsKey(script.Language))
                throw new Exception("Unknown or unsupported language");

            string providerName = compilerInfo[script.Language].CodeDomProviderType.FullName;
            CodeDomProvider provider;

            if (!compilers.ContainsKey(providerName))
            {
                provider = compilerInfo[script.Language].CreateProvider();
                compilers.Add(providerName, provider);
            }
            else
            {
                provider = compilers[providerName];
            }

            CompilerParameters parameters = new CompilerParameters(script.referencedAssemblies.ToArray())
            {
                GenerateExecutable = false,
                GenerateInMemory = true,
                OutputAssembly = rng.Next().ToString() + ".dll"
            };

            script.results = provider.CompileAssemblyFromSource(parameters, script.Source);

            script.Compiled = !script.results.Errors.HasErrors;

            if (script.Compiled)
            {
                script.assembly = script.results.CompiledAssembly;
            }
        }
示例#19
0
		public void Interop_Event_TwoObjects()
		{
			int invocationCount = 0;
			UserData.RegisterType<SomeClass>();
			UserData.RegisterType<EventArgs>();

			Script s = new Script(CoreModules.None);

			var obj = new SomeClass();
			var obj2 = new SomeClass();
			s.Globals["myobj"] = obj;
			s.Globals["myobj2"] = obj2;
			s.Globals["ext"] = DynValue.NewCallback((c, a) => { invocationCount += 1; return DynValue.Void; });

			s.DoString(@"
				function handler(o, a)
					ext();
				end

				myobj.MyEvent.add(handler);
				");

			obj.Trigger_MyEvent();
			obj2.Trigger_MyEvent();

			Assert.AreEqual(1, invocationCount);
		}
示例#20
0
		public void Test_ConstIntFieldSetter(InteropAccessMode opt)
		{
			try
			{
				string script = @"    
				myobj.ConstIntProp = 1;
				return myobj.ConstIntProp;";

				Script S = new Script();

				SomeClass obj = new SomeClass() { IntProp = 321 };

				UserData.UnregisterType<SomeClass>();
				UserData.RegisterType<SomeClass>(opt);

				S.Globals.Set("myobj", UserData.Create(obj));

				DynValue res = S.DoString(script);

				Assert.AreEqual(DataType.Number, res.Type);
				Assert.AreEqual(115, res.Number);
			}
			catch (ScriptRuntimeException)
			{
				return;
			}

			Assert.Fail();
		}
示例#21
0
        public void RunScript(Script script)
        {
            using (StringReader reader = new StringReader(script.ScriptText))
            {
                string textLine;
                StringBuilder commandText = new StringBuilder();
                while ((textLine = reader.ReadLine()) != null)
                {
                    if (textLine.Trim().ToUpperInvariant() == "GO")
                    {
                        ExecuteCommand(commandText.ToString(), script);
                        commandText.Clear();
                    }
                    else
                    {
                        commandText.AppendLine(textLine);
                    }
                }

                // If there is no GO in the SQL statement then run the entire statement
                if (commandText.Length > 0)
                {
                    ExecuteCommand(commandText.ToString(), script);
                }
            }
        }
		public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer)
		{
			var multiSigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey);
			TransactionSignature[] signatures = new TransactionSignature[multiSigParams.PubKeys.Length];
			var keys =
				multiSigParams
				.PubKeys
				.Select(p => keyRepo.FindKey(p.ScriptPubKey))
				.ToArray();

			int sigCount = 0;
			for(int i = 0 ; i < keys.Length ; i++)
			{
				if(sigCount == multiSigParams.SignatureCount)
					break;
				if(keys[i] != null)
				{
					var sig = signer.Sign(keys[i]);
					signatures[i] = sig;
					sigCount++;
				}
			}

			IEnumerable<TransactionSignature> sigs = signatures;
			if(sigCount == multiSigParams.SignatureCount)
			{
				sigs = sigs.Where(s => s != TransactionSignature.Empty && s != null);
			}
			return PayToMultiSigTemplate.Instance.GenerateScriptSig(sigs);
		}
        public override object Execute(Script script, Scope scope, Token previousToken, object unknown)
        {
            object lhs = null;
            object rhs = null;

            // Evaluate the sides.
            for (int i = 0; i < _lhs.Count; i++)
            {
                lhs = _lhs[i].Execute(script, scope, previousToken, lhs);
            }
            for (int i = 0; i < _rhs.Count; i++)
            {
                rhs = _rhs[i].Execute(script, scope, previousToken, rhs);
            }

            switch (_type)
            {
                case OperatorType.Equals:
                    return Equals(lhs, rhs);
                case OperatorType.NotEquals:
                    return !Equals(lhs, rhs);
                case OperatorType.GreaterThanOrEqual:
                    return ReflectOpMethod("op_GreaterThanOrEqual", lhs, rhs);
                case OperatorType.LessThanOrEqual:
                    return ReflectOpMethod("op_LessThanOrEqual", lhs, rhs);
                case OperatorType.GreaterThan:
                    return ReflectOpMethod("op_GreaterThan", lhs, rhs);
                case OperatorType.LessThan:
                    return ReflectOpMethod("op_LessThan", lhs, rhs);
                default:
                    break;
            }

            return null;
        }
示例#24
0
        public dynamic Execute(Script script)
        {
            if (script == null)
                throw new ArgumentNullException("script");

            return script.Execute(this.executionContext);
        }
示例#25
0
		public void Test_NIntPropertyGetter(InteropAccessMode opt)
		{
			string script = @"    
				x = myobj1.NIntProp;
				y = myobj2.NIntProp;
				return x,y;";

			Script S = new Script();

			SomeClass obj1 = new SomeClass() { NIntProp = 321 };
			SomeClass obj2 = new SomeClass() { NIntProp = null };

			UserData.UnregisterType<SomeClass>();
			UserData.RegisterType<SomeClass>(opt);

			S.Globals.Set("myobj1", UserData.Create(obj1));
			S.Globals.Set("myobj2", UserData.Create(obj2));

			DynValue res = S.DoString(script);

			Assert.AreEqual(DataType.Tuple, res.Type);
			Assert.AreEqual(321.0, res.Tuple[0].Number);
			Assert.AreEqual(DataType.Number, res.Tuple[0].Type);
			Assert.AreEqual(DataType.Nil, res.Tuple[1].Type);
		}
示例#26
0
 public NpcState(Npc Npc, MapState MapState, Script AI, Fraction Fraction, MapPoint Position)
     : base(Npc)
 {
     this.MapState = MapState;
     //this.MapActiveObjectGuid = this.MapState.AddActiveObject(this.Npc.MapActiveObject, Position);
     this.AI = AI;
     this.Fraction = Fraction;
 }
示例#27
0
		public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer)
		{
			var key = keyRepo.FindKey(scriptPubKey);
			if(key == null)
				return null;
			var sig = signer.Sign(key);
			return PayToPubkeyTemplate.Instance.GenerateScriptSig(sig);
		}
示例#28
0
        public override Token Build(Token lastToken, ScriptEngine engine, Script script, ref SourceCode sourceCode)
        {
            sourceCode++;

            engine.AddPostBuildOperation(new NotToken.NotPass(), 1000);

            return new NotToken();
        }
 public BuildLabelsFilter(BuildLabelsFilter rhs)
     : base(rhs)
 {
     text_script = rhs.text_script;
     font_size_script = rhs.font_size_script;
     disable_depth_test = rhs.disable_depth_test;
     font_name = rhs.font_name;
 }
 public ExecutionException(Script script, String strMessage)
     : base(strMessage)
 {
     if (script != null) {
         StackInfo stackInfo = script.GetCurrentStackInfo();
         if (stackInfo != null) m_Source = stackInfo.Breviary + ":" + stackInfo.Line + ": ";
     }
 }