public void Execute(InterpreterState state) { if (state.InDebugMode) { state.BreakpointTriggered = true; } }
public override void Execute(InterpreterState state) { var right = state.Stack.Peek(); state.Stack.Pop(); var left = state.Stack.Peek(); state.Stack.Pop(); switch (left.Type) { case ObjectType.TRUE: { switch (right.Type) { case ObjectType.TRUE: { state.Stack.Push(ObjectFactory.True); } break; case ObjectType.FALSE: { state.Stack.Push(ObjectFactory.True); } break; default: throw new InterpreterException("Type mismatch on '||' operator."); } } break; case ObjectType.FALSE: { switch (right.Type) { case ObjectType.TRUE: { state.Stack.Push(ObjectFactory.True); } break; case ObjectType.FALSE: { state.Stack.Push(ObjectFactory.False); } break; default: throw new InterpreterException("Type mismatch on '||' operator."); } } break; default: throw new InterpreterException("Invalid arguments to '||' operator."); } }
private static RubyArray /*!*/ AddBacktrace(RubyArray /*!*/ result, InterpreterState /*!*/ frame, int skipFrames) { do { if (skipFrames == 0) { string methodName; // TODO: generalize for all languages if (frame.ScriptCode.LanguageContext is RubyContext) { methodName = ParseRubyMethodName(frame.Lambda.Name); } else { methodName = frame.Lambda.Name; } result.Add(MutableString.Create(FormatFrame( frame.ScriptCode.SourceUnit.Path, frame.CurrentLocation.Line, methodName ))); } else { skipFrames--; } frame = frame.Caller; } while (frame != null); return(result); }
internal override object GetValue(InterpreterState state, bool outParam) { if (outParam) { return null; } return base.GetValue(state, outParam); }
internal void SetInterpretedTrace(InterpreterState /*!*/ state) { Debug.Assert(!_backtraceInitialized); // we need to copy the trace since the source locations in frames above catch site could be altered by further interpretation: _backtrace = AddBacktrace(new RubyArray(), state, 0); _backtraceInitialized = true; }
public void Execute(InterpreterState state) { state.Pointer--; if (state.Pointer < 0) { state.Pointer = Config.InterpreterMemorySize - 1; } }
internal override void Execute(InterpreterState state, SourceCode code, BaseInterpreterStack stack) { dynamic result = PropertyNameAndExpression(stack); if (result.PropertyName == Constants.KeyWords.Pop) Environment(state).Push(result.Expression); else Environment(state)[result.PropertyName] = result.Expression; }
public static void Debug(this InterpreterState state) { var funcName = string.Format("(in {0}.{1})", state.Current.Ns.Name, state.Current.Func.Name.Value); var unit = state.Current.Func.Unit; var statementIndex = RangeFinder.Find(state.Debug_CurrentStatement).From; System.Diagnostics.Debug.WriteLine(ErrorHelper.GetErrorDesc(unit.Filename, unit.Source, statementIndex, funcName)); }
public void Execute(InterpreterState state) { state.Memory[state.Pointer]--; if (state.Memory[state.Pointer] > (char)0) { state.Memory[state.Pointer] = (char)255; } }
public Interpreter() { interpreterState = InterpreterState.NOT_STARTED; programPointer = 0; programCounter = 0; inputPointer = 0; tapePointerMaximum = 0; }
public override void Execute(InterpreterState state) { if (state.Stack.Peek().Type == ObjectType.FALSE) { state.Frames.Peek().Address = (int)Argument; } state.Stack.Pop(); }
/// <summary> /// 运行解释器,直到所有语句运行完成。 /// </summary> public void Run() { State = InterpreterState.Runnig; while (Statement.Reducible && State != InterpreterState.Stop) { Reduce(); } }
public void Execute(InterpreterState state) { state.Pointer++; if (state.Pointer > Config.InterpreterMemorySize - 1) { state.Pointer = 0; } }
public override void Execute(InterpreterState state) { if (!state.Stack.Peek().TryGetTable(out Table t)) { throw new InterpreterException($"expected 'table' object on top of stack."); } state.Stack.Pop(); state.Stack.Push(new Number(t.Count)); // push table element count }
static object RunMain(Program program, string[] args) { var ins = new InterpreterState { Frames = new Stack <Frame>(), Locals = new List <LocalVariable>(), Top = program.Top, FakeCommandLineArgs = args }; var main = (FunctionDef)program.Top.Members["main"]; return(Interpreter.EvalFunction(ins, main)); }
public void Execute(InterpreterState state) { var value = state.Memory[state.Pointer]; if (state.Memory[state.Pointer] > (char)255) { state.Memory[state.Pointer] = (char)0; } }
public override void Execute(InterpreterState state) { if (!VariableName.TryGetString(out StringObj s)) { throw new InterpreterException($"Instruction object was of type '{VariableName.TypeName}', expected 'string'."); } var scope = state.Scopes.Peek(); scope.Define(s.Text, state.Stack.Peek()); }
private static object DoExecute(InterpreterState state, LambdaExpression lambda) { object ret = Interpreter.Interpret(state, lambda.Body); ControlFlow cf = ret as ControlFlow; if (cf != null) { return cf.Value; } else { return ret; } }
private static object[] ParseArgs(List <List <Token <TokenType> > > args, InterpreterState state) { if (args.Count == 1 && args[0].Count == 0) { return(new object[0]); } return(args .Select(list => state.evaluator.Evaluate(list.AsString())) .ToArray()); }
/// <summary> /// Gets the delegate associated with the LambdaExpression. /// Either it uses cached MethodInfo and creates delegate from it, or it will generate /// completely new dynamic method, store it in a cache and use it to create the delegate. /// </summary> private static Delegate GetDelegateForInterpreter(InterpreterState state, LambdaExpression lambda) { MethodInfo method; if (!LambdaInvoker.TryGetGenericInvokeMethod(lambda.Parameters.Count, out method) || HasByRefParameter(lambda)) { return GenerateDelegateForInterpreter(state, lambda); } Type[] signature = GetSignature(lambda); method = method.MakeGenericMethod(signature); return ReflectionUtils.CreateDelegate(method, lambda.Type, new LambdaInvoker(lambda, state)); }
public override void Run(ref InterpreterState state) { // If the if statement was successful, dont run if (state.LastIfResult) { return; } state.LastIfResult = false; // If statement is complete base.RunAllNodes(ref state); }
public override void Execute(InterpreterState state) { if (state.Frames.Peek().Function?.Name == "main") // if function main() returns an object, return the value to the C# object calling the script { ScriptExecutionFinished = true; ReturnObject = state.Stack.Pop(); } state.Frames.Pop(); state.Scopes.Pop(); }
/// <summary> /// Updates the gui on interpreter state change. /// </summary> /// <param name="state">The state of the interpreter</param> /// <param name="pc">The current program counter</param> public void InterPreterStateChanged(InterpreterState state, uint pc) { if (tbxOutput.InvokeRequired) { BeginInvoke((MethodInvoker)delegate() { InterPreterStateChanged(state, pc); }); return; } setControls(state); lblBrainfuckAllapot.Text = getStatus(state); lblProgramCounter.Text = pc.ToString(); }
public override void Execute(InterpreterState state) { if (_instanceName != null) // find instance using variable name { state.Scopes.Peek().Find(_instanceName.Text).As <Instance>().Scope.Set(_memberName.Text, state.Stack.Peek()); } else // current scope is function scope, parent should be class scope { state.Scopes.Peek().Parent.Set(_memberName.Text, state.Stack.Peek()); } }
public void Execute(InterpreterState state) { if (state.Memory[state.Pointer] != 0) { state.ProgramCounter = state.CallStack.Last(); } else { state.CallStack.RemoveAt(state.CallStack.Count - 1); } }
public FunctionBodyValidator(Function function) { _localContext = ExecutorContextFactory.CreateLocalContext(); foreach (var variable in function.Parameters) { _localContext._variablesRepository.Add(variable, 0); } _validatorStack = new ValidatorLexemesStack(); _validatorState = new OpeningBracketOperatorState(); }
internal MatchAnalyzer Absorb(InterpreterState state, string cmd, Regex r) { var m = r.Match(Source); PropertyName = m.Groups["var"].Value; if (m.Groups["expr"].Success) { string expr = m.Groups["expr"].Value; Tuple<string, ANALFUNC> helper = AnalysisHelpers.FirstOrDefault(t => t.Item1 == cmd) ?? AnalysisHelpers.First(t => t.Item1.Contains(expr.Substring(0, 1))); RealizedObject = new WARPObject(helper.Item2(state, expr)); } return this; }
public static _7sFunction GetFunction(InterpreterState state, string name) { // If function exists, return it, otherwise return null foreach (var f in state.Functions) { if (f.Name.Equals(name)) { return(f); } } return(null); }
/// <summary> /// IceKori 解释器对象。 /// </summary> /// <param name="commonVariables">公共变量列表</param> /// <param name="commonCommands">公共指令列表</param> /// <param name="globalVariables">全局变量列表</param> /// <param name="globalCommands">全局指令列表</param> /// <param name="commands">指令列表</param> public Interpreter(Dictionary <string, BaseExpression> commonVariables, Dictionary <string, List <BaseStatement> > commonCommands, Dictionary <string, IceKoriBaseType> globalVariables, Dictionary <string, List <BaseStatement> > globalCommands, List <BaseStatement> commands) { ErrorHandling = new ErrorHandling(); Env = new Enviroment(this, commonVariables, commonCommands, globalVariables, globalCommands); Statement = new Sequence(commands); _DefaultDefine(); State = InterpreterState.Pending; }
public InterpreterState AppendSymbol(Symbol symbol) { _validatorState = _validatorState.MoveToNextState(symbol, _validatorStack, _localContext); _validatorState.Execute(_validatorStack, _localContext); if (_validatorState is FunctionSignatureStartState || _validatorState is AssignmentOperatorState) { return(new ErrorState(symbol)); } return(_validatorState); }
public MudInterpreter(MudServer server, MudConnection con, Dungeon dungeon) { Server = server; this.dungeon = dungeon; Connection = con; status = InterpreterState.NeworContinue; con.SendString("Create a new character or continue (N/C): "); Commands.Add("help", new Action <string>(HelpCommand)); Commands.Add("status", new Action <string>(StatusCommand)); Commands.Add("inventory", new Action <string>(InventoryCommand)); Commands.Add("examine", new Action <string>(ExamineCommand)); salt = GenerateSalt(); }
public override void Run(ref InterpreterState state) { state.Reset(); try { foreach (Node child in Children) { child.Run(ref state); } } catch (InterpreterException e) { Utils.PrintError(e); } }
private void _WaiteTime() { if (Env.GetTopVariables().ContainsKey("$TIMER")) { var timer = ((IceKoriDataTime)Env.GetTopVariables()["$TIMER"]).Value; var date = ((IceKoriInt)Env.GetTopVariables()["$DATE"]).Value; if ((DateTime.Now - timer).Ticks >= date * 10000000) { Env.GetTopVariables().Remove("$TIMER"); Env.GetTopVariables().Remove("$DATE"); State = InterpreterState.Runnig; _Reduce(); } } }
public override void Execute(InterpreterState state) { var value = state.Stack.Pop(); var defined = state.Environment.Globals.Scope.Find(VariableName.ToString()); if (defined != null) { if (defined != value) { throw new InterpreterException($"Initializing a global variable ('{VariableName}') with two different values ('{defined}' and '{value}') is not possible."); } return; } state.Environment.Globals.Scope.Define(VariableName.ToString(), value); }
public override void Execute(InterpreterState state) { // TODO add helpful exceptions if instance or memberName are of the wrong type var instance = state.Stack.Peek(); state.Stack.Pop(); var memberName = state.Stack.Peek(); state.Stack.Pop(); var value = instance.As <Instance>().Scope.Find(memberName.As <StringObj>().Text); state.Stack.Push(value); }
internal static CMD Gather(InterpreterState state, string key, Builder bld) { ExecutionSupport.Emit(() => string.Format("Command created: {0}, Source Position {1}", key, state.Source().SourcePosition)); state.Source().Advance(); ActionCommand<PropertyBasedExecutionEnvironment> cmd = new ActionCommand<PropertyBasedExecutionEnvironment>(bld.Action, key); if (bld.Expression != null) { MatchAnalyzer a = bld.Examine(state, key); Action<WARPObject> pushIfNonEmpty = o => { if (o != null && !String.IsNullOrEmpty(o.AsString())) cmd.ExecutionContext.Enqueue(o); }; pushIfNonEmpty(a.RealizedObject); pushIfNonEmpty(new WARPObject(a.PropertyName)); ExecutionSupport.Emit(() => string.Concat("Command input parsed: ", a.Source)); } return cmd; }
public double?Execute(string expression) { var state = InterpreterState.StartFromInitialState(_stack); for (var index = 0; index < expression.Length; index++) { var symbol = SymbolFactory.CreateSymbol(expression, index); state = state.MoveToNextState(symbol, _stack, _context); state.Execute(_stack, _context); } state = state.MoveToFinalState(expression.Length, _stack, _context); state.Execute(_stack, _context); return(_stack.GetResult(_context)); }
public override void Run(ref InterpreterState state) { try { state.RunWithVariables((ref Dictionary <string, object> vars) => { dynamic x = vars[variableName]; x++; vars[variableName] = x; }); } catch { throw new InterpreterException($"Tried to increment a non-number variable \"{variableName}\" at {linePosition}"); } }
/// <summary> /// Called by the code:LambdaInvoker.Invoke from the delegate generated below by /// code:GetDelegateForInterpreter. /// /// This method must repackage arguments to match the lambdas signature, which /// may mean repackaging the parameter arrays. /// /// Input are two arrays - regular arguments passed into the generated delegate, /// and (if the delegate had params array), the parameter array, separately. /// </summary> internal static object InterpretLambda(InterpreterState lexicalParentState, LambdaExpression lambda, object[] args) { Assert.NotNull(lexicalParentState, lambda, args); var state = InterpreterState.Current.Update( (caller) => lexicalParentState.CreateForLambda(lambda, caller, args) ); try { object result = Interpret(state, lambda.Body); var cf = result as ControlFlow; if (cf != null) { return (cf.Kind == ControlFlowKind.Yield) ? cf.Value : null; } return result; } finally { InterpreterState.Current.Value = state.Caller; } }
protected static PropertyBasedExecutionEnvironment Environment(InterpreterState state) { return state.GetExecutionEnvironment<PropertyBasedExecutionEnvironment>(); }
private static Delegate GenerateDelegateForInterpreter(InterpreterState state, LambdaExpression lambda) { if (_Delegates == null) { Interlocked.CompareExchange<WeakDictionary<LambdaExpression, MethodInfo>>( ref _Delegates, new WeakDictionary<LambdaExpression, MethodInfo>(), null ); } bool found; MethodInfo method; // // LOCK to find the MethodInfo // lock (_Delegates) { found = _Delegates.TryGetValue(lambda, out method); } if (!found) { method = CreateDelegateForInterpreter(lambda.Type); // // LOCK to store the MethodInfo // (and maybe find one added while we were creating new delegate, in which case // throw away the new one and use the one from the cache. // lock (_Delegates) { MethodInfo conflict; if (!_Delegates.TryGetValue(lambda, out conflict)) { _Delegates.Add(lambda, method); } else { method = conflict; } } } return ReflectionUtils.CreateDelegate(method, lambda.Type, new LambdaInvoker(lambda, state)); }
protected void processReceivedData(string incomingLine) { switch (interpreterState) { case InterpreterState.Idle: // Here we are waiting for a string to indicate the start of return data if (incomingLine == "!") return; else if (incomingLine.Contains("STATUS")) { // Check for correct length if (incomingLine.Length != 7) return; // Try to get focuser number char s = incomingLine[6]; int currentFocNum = 0; if (!int.TryParse(s.ToString(), out currentFocNum)) return; // validate the focuser number if (currentFocNum == 1) responseType = InterpreterResponseType.STATUS1; else if (currentFocNum == 2) responseType = InterpreterResponseType.STATUS2; else return; interpreterState = InterpreterState.WaitingForEnd; responseData.Clear(); } else if (incomingLine.Contains("CONFIG")) { // Check for correct length if (incomingLine.Length != 7) return; // Try to get focuser number char s = incomingLine[6]; int currentFocNum = 0; if (!int.TryParse(s.ToString(), out currentFocNum)) return; // validate the focuser number and set the response type if (currentFocNum == 1) { responseType = InterpreterResponseType.CONFIG1; interpreterState = InterpreterState.WaitingForEnd; } else if (currentFocNum == 2) { responseType = InterpreterResponseType.CONFIG2; interpreterState = InterpreterState.WaitingForEnd; } else return; interpreterState = InterpreterState.WaitingForEnd; responseData.Clear(); } else if (incomingLine.Contains("HUB INFO")) { responseType = InterpreterResponseType.HUBINFO; interpreterState = InterpreterState.WaitingForEnd; responseData.Clear(); } else if (incomingLine == "M") { CheckForAnotherMoveAck: if (pendingMoveAcks.Count > 0) { FocuserManualResetEvent mre = pendingMoveAcks.Dequeue(); if (mre != null) { if (mre.TimeoutOccurred) { mre = null; goto CheckForAnotherMoveAck; } else { mre.Set(); mre = null; } } } } else if (incomingLine == "SET") { CheckForAnotherSetAck: if (pendingSetAcks.Count > 0) { FocuserManualResetEvent mre = pendingSetAcks.Dequeue(); if (mre != null) { if (mre.TimeoutOccurred) // If a timeout occurred on a prior cmd request we are to assume { // that response was never received and thus we should remove it mre = null; // and trigger the next ResetEvent in the list goto CheckForAnotherSetAck; } else { mre.Set(); mre = null; } } } } else if (incomingLine == "HALTED") { CheckForAnotherHaltAck: if (pendingHaltAcks.Count > 0) { FocuserManualResetEvent mre = pendingHaltAcks.Dequeue(); if (mre != null) { if (mre.TimeoutOccurred) // If a timeout occurred on a prior cmd request we are to assume { // that response was never received and thus we should remove it mre = null; // and trigger the next ResetEvent in the list goto CheckForAnotherHaltAck; } else { mre.Set(); mre = null; } } } } else if (incomingLine == "H") { CheckForAnotherHomeAck: if (pendingHomeAcks.Count > 0) { FocuserManualResetEvent mre = pendingHomeAcks.Dequeue(); if (mre != null) { if (mre.TimeoutOccurred) // If a timeout occurred on a prior cmd request we are to assume { // that response was never received and thus we should remove it mre = null; // and trigger the next ResetEvent in the list goto CheckForAnotherHomeAck; } else { mre.Set(); mre = null; } } } } else if (incomingLine.Contains("ER=")) { EventLogger.LogMessage("Firmware error code received: " + incomingLine, System.Diagnostics.TraceLevel.Error); try { FirmwareErrorOccurred(this, new FocuserDataReceivedEventArgs(new List<string>() { incomingLine })); } catch { } } break; case InterpreterState.WaitingForEnd: if (incomingLine == "END") { switch (responseType) { case InterpreterResponseType.NONE: break; case InterpreterResponseType.CONFIG1: disconnectWatchdog = 0; Config1Received(this, new FocuserDataReceivedEventArgs(responseData)); break; case InterpreterResponseType.CONFIG2: disconnectWatchdog = 0; Config2Received(this, new FocuserDataReceivedEventArgs(responseData)); break; case InterpreterResponseType.STATUS1: disconnectWatchdog = 0; Status1Received(this, new FocuserDataReceivedEventArgs(responseData)); break; case InterpreterResponseType.STATUS2: disconnectWatchdog = 0; Status2Received(this, new FocuserDataReceivedEventArgs(responseData)); break; case InterpreterResponseType.HUBINFO: disconnectWatchdog = 0; HubInfoReceived(this, new FocuserDataReceivedEventArgs(responseData)); break; } interpreterState = InterpreterState.Idle; } else { // Add the data to the response responseData.Add(incomingLine); // Make sure we didn't miss the end. if (responseData.Count > MAX_RESPONSE_LINE_COUNT) interpreterState = InterpreterState.Idle; } break; } }
protected void processReceivedData(string incomingLine) { switch (interpreterState) { case InterpreterState.Idle: // Here we are waiting for a string to indicate the start of return data if (incomingLine == "!") return; else if (incomingLine.Contains("STATUS - FOC")) { responseType = InterpreterResponseType.FOC_STATUS; interpreterState = InterpreterState.WaitingForEnd; responseData.Clear(); } else if (incomingLine.Contains("STATUS - ROT")) { responseType = InterpreterResponseType.ROT_STATUS; interpreterState = InterpreterState.WaitingForEnd; responseData.Clear(); } else if (incomingLine.Contains("CONFIG - FOC")) { responseType = InterpreterResponseType.FOC_CONFIG; interpreterState = InterpreterState.WaitingForEnd; responseData.Clear(); } else if (incomingLine.Contains("CONFIG - ROT")) { responseType = InterpreterResponseType.ROT_CONFIG; interpreterState = InterpreterState.WaitingForEnd; responseData.Clear(); } else if (incomingLine.Contains("HUB INFO")) { responseType = InterpreterResponseType.HUBINFO; interpreterState = InterpreterState.WaitingForEnd; responseData.Clear(); } else if (incomingLine == "M") { CheckForAnotherMoveAck: if (pendingMoveAcks.Count > 0) { FocuserManualResetEvent mre = pendingMoveAcks.Dequeue(); if (mre != null) { if (mre.TimeoutOccurred) { mre = null; goto CheckForAnotherMoveAck; } else { mre.Set(); mre = null; } } } } else if (incomingLine == "SET") { CheckForAnotherSetAck: if (pendingSetAcks.Count > 0) { FocuserManualResetEvent mre = pendingSetAcks.Dequeue(); if (mre != null) { if (mre.TimeoutOccurred) // If a timeout occurred on a prior cmd request we are to assume { // that response was never received and thus we should remove it mre = null; // and trigger the next ResetEvent in the list goto CheckForAnotherSetAck; } else { mre.Set(); mre = null; } } } } else if (incomingLine == "HALTED") { CheckForAnotherHaltAck: if (pendingHaltAcks.Count > 0) { FocuserManualResetEvent mre = pendingHaltAcks.Dequeue(); if (mre != null) { if (mre.TimeoutOccurred) // If a timeout occurred on a prior cmd request we are to assume { // that response was never received and thus we should remove it mre = null; // and trigger the next ResetEvent in the list goto CheckForAnotherHaltAck; } else { mre.Set(); mre = null; } } } } else if (incomingLine == "H") { CheckForAnotherHomeAck: if (pendingHomeAcks.Count > 0) { FocuserManualResetEvent mre = pendingHomeAcks.Dequeue(); if (mre != null) { if (mre.TimeoutOccurred) // If a timeout occurred on a prior cmd request we are to assume { // that response was never received and thus we should remove it mre = null; // and trigger the next ResetEvent in the list goto CheckForAnotherHomeAck; } else { mre.Set(); mre = null; } } } } else if (incomingLine.Contains("ER=")) { EventLogger.LogMessage("Firmware error code received: " + incomingLine, System.Diagnostics.TraceLevel.Error); try { FirmwareErrorOccurred(this, new FocuserDataReceivedEventArgs(new List<string>() { incomingLine })); } catch { } } break; case InterpreterState.WaitingForEnd: if (incomingLine == "END") { switch (responseType) { case InterpreterResponseType.NONE: break; case InterpreterResponseType.FOC_CONFIG: disconnectWatchdog = 0; FocConfigReceived(this, new FocuserDataReceivedEventArgs(responseData)); break; case InterpreterResponseType.ROT_CONFIG: disconnectWatchdog = 0; RotConfigReceived(this, new FocuserDataReceivedEventArgs(responseData)); break; case InterpreterResponseType.FOC_STATUS: disconnectWatchdog = 0; FocStatusReceived(this, new FocuserDataReceivedEventArgs(responseData)); break; case InterpreterResponseType.ROT_STATUS: disconnectWatchdog = 0; RotStatusReceived(this, new FocuserDataReceivedEventArgs(responseData)); break; case InterpreterResponseType.HUBINFO: disconnectWatchdog = 0; HubInfoReceived(this, new FocuserDataReceivedEventArgs(responseData)); break; } interpreterState = InterpreterState.Idle; } else { // Add the data to the response responseData.Add(incomingLine); // Make sure we didn't miss the end. if (responseData.Count > MAX_RESPONSE_LINE_COUNT) interpreterState = InterpreterState.Idle; } break; } }
internal void SetInterpretedTrace(InterpreterState/*!*/ state) { if (_exception != _visibleException) { // Thread#raise uses Thread.Abort to raise an async exception. In such cases, a different instance of // ThreadAbortException is thrown at the end of every catch block (as long as Thread.ResetAbort is not called). // However, we only want to remember the first one as it will have the most complete stack trace. // So we ignore subsequent calls. if (_backtraceInitialized) { return; } } Debug.Assert(!_backtraceInitialized); // we need to copy the trace since the source locations in frames above catch site could be altered by further interpretation: _backtrace = AddBacktrace(new RubyArray(), state, 0); _backtraceInitialized = true; }
/// <summary> /// Parse /// </summary> /// <returns>true if success, false if failure</returns> public bool Parse() { ParseTree = null; BehaviorParser parser = new BehaviorParser(_ContextString); string error = null; try { ParseTree = parser.Parse(Input); } catch (ExpectedTokenParseException e) { error = e.Message; } catch (UnexpectedTokenParseException e) { error = e.Message; } if (error != null) { State = InterpreterState.ParseFailure; ErrorString = error; return false; } State = InterpreterState.ParseSuccess; return true; }
public IBELObject EvaluateToObject(TopicContext topicContext, ExternalReferencesMap externalWikimap) { _CacheRules = new ArrayList(); if (ParseTree == null) { ErrorString = "Expression can not be evaluated; parse failed."; State = InterpreterState.EvaluationFailure; return null; } ExecutionContext ctx = new ExecutionContext(topicContext); ctx.WikiTalkVersion = WikiTalkVersion; IBELObject answer = null; try { ctx.ExternalWikiMap = externalWikimap; IScope theScope = null; ctx.Presenter = Presenter; TopicVersionInfo topic = topicContext != null ? topicContext.CurrentTopic : null; if (topic != null && topic.TopicRevision != null) { // Locate any topics via the NamespaceWith propertyName to see // if there's anybody else we should import (for all topics in the namespace) ArrayList nswith = topicContext.CurrentFederation.GetTopicInfo(ctx, topicContext.CurrentTopic.NamespaceManager.DefinitionTopicName.DottedName).GetListProperty("NamespaceWith"); if (nswith != null) { nswith.Reverse(); foreach (string top in nswith) { QualifiedTopicRevision abs = Federation.UnambiguousTopicNameFor(new TopicRevision(top), topic.NamespaceManager.Namespace); if (abs == null) { throw new Exception("No such topic: " + top + " (as specifed in NamespaceWith: property for " + topicContext.CurrentTopic.NamespaceManager.DefinitionTopicName.DottedName + ")"); } theScope = new TopicScope(theScope, new DynamicTopic(topic.Federation, abs)); } } // Locate any topics via the with propertyName to see if there's anybody else we should import ArrayList with = topicContext.CurrentTopic.GetListProperty("With"); if (with != null) { with.Reverse(); foreach (string top in with) { QualifiedTopicRevision abs = Federation.UnambiguousTopicNameFor(new TopicRevision(top), topic.NamespaceManager.Namespace); if (abs == null) { throw new Exception("No such topic: " + top + " (as specifed in With: property for " + topicContext.CurrentTopic + ")"); } theScope = new TopicScope(theScope, new DynamicTopic(topic.Federation, abs)); } } // add the topic to the current scope (this guy goes at the front of the queue!) theScope = new TopicScope(theScope, new DynamicTopic(topic.Federation, topic.TopicRevision)); } if (theScope != null) ctx.PushScope(theScope); // make sure we can use local references // parse tree -> live objects answer = ParseTree.Expose(ctx); if (theScope != null) ctx.PopScope(); _CacheRules = ctx.CacheRules; } catch (Exception e) { _CacheRules = ctx.CacheRules; ErrorString = e.Message; State = InterpreterState.EvaluationFailure; return null; } State = InterpreterState.EvaluationSuccess; return answer; }
/// <summary> /// Sets controll buttons according to interpreter's state. /// </summary> /// <param name="state">The interpreters state</param> private void setControls(InterpreterState state) { switch (state) { case InterpreterState.STOPPED: case InterpreterState.NOT_STARTED: { btn_Stop.Enabled = false; btn_Interpretation.Enabled = true; btn_Default.Enabled = true; tbxInput.ReadOnly = false; tbxProgram.ReadOnly = false; break; } case InterpreterState.IN_PROGRESS: { btn_Stop.Enabled = true; btn_Interpretation.Enabled = false; btn_Default.Enabled = false; tbxInput.ReadOnly = true; tbxProgram.ReadOnly = true; break; } } }
internal override void Execute(InterpreterState state, SourceCode code, BaseInterpreterStack stack) { RandomAccessStack<WARPObject> st = PropertyBasedExecutionEnvironment.ScratchPad[Constants.RASName] as RandomAccessStack<WARPObject>; st.Set((int)stack.Pop<WARPObject>().AsNumeric()); Action(st, stack); }
private static RubyArray/*!*/ AddBacktrace(RubyArray/*!*/ result, InterpreterState/*!*/ frame, int skipFrames) { do { if (skipFrames == 0) { string methodName; // TODO: generalize for all languages if (frame.ScriptCode.LanguageContext is RubyContext) { methodName = ParseRubyMethodName(frame.Lambda.Name); } else { methodName = frame.Lambda.Name; } result.Add(MutableString.Create(FormatFrame( frame.ScriptCode.SourceUnit.Path, frame.CurrentLocation.Line, methodName ))); } else { skipFrames--; } frame = frame.Caller; } while (frame != null); return result; }
internal void SetInterpretedTrace(InterpreterState/*!*/ state) { Debug.Assert(!_backtraceInitialized); // we need to copy the trace since the source locations in frames above catch site could be altered by further interpretation: _backtrace = AddBacktrace(new RubyArray(), state, 0); _backtraceInitialized = true; }
internal void SetInterpretedTrace(InterpreterState/*!*/ state) { if (_backtrace != null) { return; } // we need to copy the trace since the source locations in frames above catch site could be altered by further interpretation: _backtrace = AddBacktrace(new RubyArray(), state, 0); SetBacktraceForRaise((RubyContext)state.ScriptCode.LanguageContext, _backtrace); }
private static object Interpret(InterpreterState state, Expression expr) { switch (expr.NodeType) { #region Generated Ast Interpreter // *** BEGIN GENERATED CODE *** // generated by function: gen_interpreter from: generate_tree.py case ExpressionType.Add: return InterpretBinaryExpression(state, expr); case ExpressionType.AddChecked: return InterpretBinaryExpression(state, expr); case ExpressionType.And: return InterpretBinaryExpression(state, expr); case ExpressionType.AndAlso: return InterpretAndAlsoBinaryExpression(state, expr); case ExpressionType.ArrayLength: return InterpretUnaryExpression(state, expr); case ExpressionType.ArrayIndex: return InterpretBinaryExpression(state, expr); case ExpressionType.Call: return InterpretMethodCallExpression(state, expr); case ExpressionType.Coalesce: return InterpretCoalesceBinaryExpression(state, expr); case ExpressionType.Conditional: return InterpretConditionalExpression(state, expr); case ExpressionType.Constant: return InterpretConstantExpression(state, expr); case ExpressionType.Convert: return InterpretConvertUnaryExpression(state, expr); case ExpressionType.ConvertChecked: return InterpretConvertUnaryExpression(state, expr); case ExpressionType.Divide: return InterpretBinaryExpression(state, expr); case ExpressionType.Equal: return InterpretBinaryExpression(state, expr); case ExpressionType.ExclusiveOr: return InterpretBinaryExpression(state, expr); case ExpressionType.GreaterThan: return InterpretBinaryExpression(state, expr); case ExpressionType.GreaterThanOrEqual: return InterpretBinaryExpression(state, expr); case ExpressionType.Invoke: return InterpretInvocationExpression(state, expr); case ExpressionType.Lambda: return InterpretLambdaExpression(state, expr); case ExpressionType.LeftShift: return InterpretBinaryExpression(state, expr); case ExpressionType.LessThan: return InterpretBinaryExpression(state, expr); case ExpressionType.LessThanOrEqual: return InterpretBinaryExpression(state, expr); case ExpressionType.ListInit: return InterpretListInitExpression(state, expr); case ExpressionType.MemberAccess: return InterpretMemberExpression(state, expr); case ExpressionType.MemberInit: return InterpretMemberInitExpression(state, expr); case ExpressionType.Modulo: return InterpretBinaryExpression(state, expr); case ExpressionType.Multiply: return InterpretBinaryExpression(state, expr); case ExpressionType.MultiplyChecked: return InterpretBinaryExpression(state, expr); case ExpressionType.Negate: return InterpretUnaryExpression(state, expr); case ExpressionType.UnaryPlus: return InterpretUnaryExpression(state, expr); case ExpressionType.NegateChecked: return InterpretUnaryExpression(state, expr); case ExpressionType.New: return InterpretNewExpression(state, expr); case ExpressionType.NewArrayInit: return InterpretNewArrayExpression(state, expr); case ExpressionType.NewArrayBounds: return InterpretNewArrayExpression(state, expr); case ExpressionType.Not: return InterpretUnaryExpression(state, expr); case ExpressionType.NotEqual: return InterpretBinaryExpression(state, expr); case ExpressionType.Or: return InterpretBinaryExpression(state, expr); case ExpressionType.OrElse: return InterpretOrElseBinaryExpression(state, expr); case ExpressionType.Parameter: return InterpretParameterExpression(state, expr); case ExpressionType.Power: return InterpretBinaryExpression(state, expr); case ExpressionType.Quote: return InterpretQuoteUnaryExpression(state, expr); case ExpressionType.RightShift: return InterpretBinaryExpression(state, expr); case ExpressionType.Subtract: return InterpretBinaryExpression(state, expr); case ExpressionType.SubtractChecked: return InterpretBinaryExpression(state, expr); case ExpressionType.TypeAs: return InterpretUnaryExpression(state, expr); case ExpressionType.TypeIs: return InterpretTypeBinaryExpression(state, expr); case ExpressionType.Assign: return InterpretAssignBinaryExpression(state, expr); case ExpressionType.Block: return InterpretBlockExpression(state, expr); case ExpressionType.DebugInfo: return InterpretDebugInfoExpression(state, expr); case ExpressionType.Decrement: return InterpretUnaryExpression(state, expr); case ExpressionType.Dynamic: return InterpretDynamicExpression(state, expr); case ExpressionType.Default: return InterpretDefaultExpression(state, expr); case ExpressionType.Extension: return InterpretExtensionExpression(state, expr); case ExpressionType.Goto: return InterpretGotoExpression(state, expr); case ExpressionType.Increment: return InterpretUnaryExpression(state, expr); case ExpressionType.Index: return InterpretIndexExpression(state, expr); case ExpressionType.Label: return InterpretLabelExpression(state, expr); case ExpressionType.RuntimeVariables: return InterpretRuntimeVariablesExpression(state, expr); case ExpressionType.Loop: return InterpretLoopExpression(state, expr); case ExpressionType.Switch: return InterpretSwitchExpression(state, expr); case ExpressionType.Throw: return InterpretThrowUnaryExpression(state, expr); case ExpressionType.Try: return InterpretTryExpression(state, expr); case ExpressionType.Unbox: return InterpretUnboxUnaryExpression(state, expr); case ExpressionType.TypeEqual: return InterpretTypeBinaryExpression(state, expr); case ExpressionType.OnesComplement: return InterpretUnaryExpression(state, expr); case ExpressionType.IsTrue: return InterpretUnaryExpression(state, expr); case ExpressionType.IsFalse: return InterpretUnaryExpression(state, expr); case ExpressionType.AddAssign: case ExpressionType.AndAssign: case ExpressionType.DivideAssign: case ExpressionType.ExclusiveOrAssign: case ExpressionType.LeftShiftAssign: case ExpressionType.ModuloAssign: case ExpressionType.MultiplyAssign: case ExpressionType.OrAssign: case ExpressionType.PowerAssign: case ExpressionType.RightShiftAssign: case ExpressionType.SubtractAssign: case ExpressionType.AddAssignChecked: case ExpressionType.MultiplyAssignChecked: case ExpressionType.SubtractAssignChecked: case ExpressionType.PreIncrementAssign: case ExpressionType.PreDecrementAssign: case ExpressionType.PostIncrementAssign: case ExpressionType.PostDecrementAssign: return InterpretReducibleExpression(state, expr); // *** END GENERATED CODE *** #endregion default: throw Assert.Unreachable; }; }
internal override void Execute(InterpreterState state, SourceCode code, BaseInterpreterStack stack) { var obj = stack.Pop<WARPObject>(); PropertyBasedExecutionEnvironment env = Environment(state); if (!env.HasScratchPadEntry(Constants.KeyWords.Comparison)) { stack.Push(obj); PropertyBasedExecutionEnvironment.ScratchPad[Constants.KeyWords.Comparison] = String.Empty; } else { var lhs = stack.Pop<WARPObject>(); PropertyBasedExecutionEnvironment.ScratchPad.Remove(Constants.KeyWords.Comparison); var bothNumeric = lhs.IsNumeric && obj.IsNumeric; Func<int> cmp = () => { var f = lhs.AsNumeric(); var s = obj.AsNumeric(); return (f < s ? -1 : (f > s ? 1 : 0)); }; stack.Push(new WARPObject(bothNumeric ? cmp() : string.Compare(lhs.AsString(), obj.AsString()))); } }
/// <summary> /// Returns the status string of an interpreter state. /// </summary> /// <param name="state">The interpreters state</param> /// <returns>String representation of an interpreter state</returns> private string getStatus(InterpreterState state) { switch (state) { case InterpreterState.NOT_STARTED: return "Nem elkezdett"; case InterpreterState.IN_PROGRESS: return "Folyamatban"; case InterpreterState.STOPPED: return "Vége"; default: return "Ismeretlen"; } }
internal InterpreterVariables(InterpreterState state, RuntimeVariablesExpression node) { _state = state; _vars = node.Variables; }
internal abstract void Execute(InterpreterState state, SourceCode code, BaseInterpreterStack stack);
internal WARPObject Fabricate(InterpreterState state, string symbol) { return mHandlers[symbol](state); }
internal override void Execute(InterpreterState state, SourceCode code, BaseInterpreterStack stack) { var obj = stack.Pop(); stack.Pop(); stack.Push(obj); }
internal override void Execute(InterpreterState state, SourceCode code, BaseInterpreterStack stack) { var val = ((WARPObject)Environment(state)[stack.Pop<WARPObject>().AsString()]).AsString(); state.AddExecutionEnvironment<PropertyBasedExecutionEnvironment>(); val.Reverse().ToList().ForEach(c => Environment(state).Push(new WARPObject(new string(new[] { c })))); }
internal override void Execute(InterpreterState state, SourceCode source, BaseInterpreterStack stack) { dynamic result = PropertyNameAndExpression(stack); bool inPopMode = result.PropertyName == Constants.KeyWords.Pop; var pbee = Environment(state); Int64 cur = inPopMode ? stack.Pop<WARPObject>().AsNumeric() : pbee[result.PropertyName].As<WARPObject>().AsNumeric(); var obj = new WARPObject(FlexibleNumeralSystem.Encode(Command(cur, result.Expression), WARPObject.CurrentRadix)); if (result.PropertyName == Constants.KeyWords.Pop) pbee.Push(obj); else pbee[result.PropertyName] = obj; }