Exemplo n.º 1
0
        private static List<IToken> ConvertToPostfixForm( List<IToken> infixExpression )
        {
            var evaluationState = new EvaluationState();
            foreach( var token in infixExpression )
                token.ConvertToPostfixForm( evaluationState );

            return evaluationState.PostfixExpression;
        }
Exemplo n.º 2
0
		public EvaluationResult Evaluate(EvaluationState state, ReadOnlyList<IEvaluate> args, ReadOnlyList<Object> data)
		{
			Combat.Character character = state.Character as Combat.Character;
			if (character == null) return new EvaluationResult();

			EvaluationResult result = args[1].Evaluate(state);
			if (result.ResultType == ResultType.None) return new EvaluationResult();

			FuncCaller varcaller = args[0] as FuncCaller;
			if (varcaller == null) return new EvaluationResult();

			if (varcaller.Function is Triggers.Var)
			{
				EvaluationResult varindex = varcaller.Args[0].Evaluate(state);
				if (varindex.ResultType == ResultType.None) return new EvaluationResult();

				if (character.Variables.SetInterger(varindex.IntValue, false, result.IntValue) == false)
				{
					return new EvaluationResult();
				}
			}
			else if (varcaller.Function is Triggers.FVar)
			{
				EvaluationResult varindex = varcaller.Args[0].Evaluate(state);
				if (varindex.ResultType == ResultType.None) return new EvaluationResult();

				if (character.Variables.SetFloat(varindex.IntValue, false, result.FloatValue) == false)
				{
					return new EvaluationResult();
				}
			}
			else if (varcaller.Function is Triggers.SysVar)
			{
				EvaluationResult varindex = varcaller.Args[0].Evaluate(state);
				if (varindex.ResultType == ResultType.None) return new EvaluationResult();

				if (character.Variables.SetInterger(varindex.IntValue, true, result.IntValue) == false)
				{
					return new EvaluationResult();
				}
			}
			else if (varcaller.Function is Triggers.SysFVar)
			{
				EvaluationResult varindex = varcaller.Args[0].Evaluate(state);
				if (varindex.ResultType == ResultType.None) return new EvaluationResult();

				if (character.Variables.SetFloat(varindex.IntValue, true, result.FloatValue) == false)
				{
					return new EvaluationResult();
				}
			}
			else
			{
				return new EvaluationResult();
			}

			return result;
		}
Exemplo n.º 3
0
		public EvaluationResult Evaluate(EvaluationState state, ReadOnlyList<IEvaluate> args, ReadOnlyList<Object> data)
		{
			EvaluationResult checkagainst = args[0].Evaluate(state);
			EvaluationResult first = args[1].Evaluate(state);
			EvaluationResult second = args[2].Evaluate(state);

			Operator compare = (Operator)data[0];
			Symbol pre_op = (Symbol)data[1];
			Symbol post_op = (Symbol)data[2];

			return BaseOperations.Range(checkagainst, first, second, compare, pre_op, post_op);
		}
Exemplo n.º 4
0
            /// <summary>
            /// Loads references, set options and execute files specified in the initialization file.
            /// Also prints logo unless <paramref name="isRestarting"/> is true.
            /// </summary>
            private async Task<EvaluationState> InitializeContextAsync(
                Task<EvaluationState> lastTask,
                RemoteAsyncOperation<RemoteExecutionResult> operation,
                string initializationFileOpt,
                bool isRestarting)
            {
                Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));

                var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);

                try
                {
                    // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(_replServiceProvider.Logo);
                    }

                    if (File.Exists(initializationFileOpt))
                    {
                        Console.Out.WriteLine(string.Format(FeaturesResources.Loading_context_from_0, Path.GetFileName(initializationFileOpt)));
                        var parser = _replServiceProvider.CommandLineParser;

                        // The base directory for relative paths is the directory that contains the .rsp file.
                        // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
                        var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
                        var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null);

                        foreach (var error in args.Errors)
                        {
                            var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
                            writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
                        }

                        if (args.Errors.Length == 0)
                        {
                            var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);
                            var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory);

                            var metadataReferences = new List<PortableExecutableReference>();
                            foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
                            {
                                // interactive command line parser doesn't accept modules or linked assemblies
                                Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);

                                var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
                                if (!resolvedReferences.IsDefaultOrEmpty)
                                {
                                    metadataReferences.AddRange(resolvedReferences);
                                }
                            }

                            var scriptPathOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path;

                            var rspState = new EvaluationState(
                                state.ScriptStateOpt,
                                state.ScriptOptions.
                                    WithFilePath(scriptPathOpt).
                                    WithReferences(metadataReferences).
                                    WithImports(CommandLineHelpers.GetImports(args)).
                                    WithMetadataResolver(metadataResolver).
                                    WithSourceResolver(sourceResolver),
                                args.SourcePaths,
                                args.ReferencePaths,
                                rspDirectory);

                            _globals.ReferencePaths.Clear();
                            _globals.ReferencePaths.AddRange(args.ReferencePaths);

                            _globals.SourcePaths.Clear();
                            _globals.SourcePaths.AddRange(args.SourcePaths);

                            _globals.Args.AddRange(args.ScriptArguments);

                            if (scriptPathOpt != null)
                            {
                                var newScriptState = await TryExecuteFileAsync(rspState, scriptPathOpt).ConfigureAwait(false);
                                if (newScriptState != null)
                                {
                                    // remove references and imports from the options, they have been applied and will be inherited from now on:
                                    rspState = rspState.
                                        WithScriptState(newScriptState).
                                        WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences());
                                }
                            }

                            state = rspState;
                        }
                    }

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(FeaturesResources.Type_Sharphelp_for_more_information);
                    }
                }
                catch (Exception e)
                {
                    ReportUnhandledException(e);
                }
                finally
                {
                    state = CompleteExecution(state, operation, success: true);
                }

                return state;
            }
Exemplo n.º 5
0
            public Service()
            {
                var initialState = new EvaluationState(
                    scriptStateOpt: null,
                    scriptOptions: ScriptOptions.Default,
                    sourceSearchPaths: ImmutableArray<string>.Empty,
                    referenceSearchPaths: ImmutableArray<string>.Empty,
                    workingDirectory: Directory.GetCurrentDirectory());

                _lastTask = Task.FromResult(initialState);

                Console.OutputEncoding = Encoding.UTF8;

                // We want to be sure to delete the shadow-copied files when the process goes away. Frankly
                // there's nothing we can do if the process is forcefully quit or goes down in a completely
                // uncontrolled manner (like a stack overflow). When the process goes down in a controlled
                // manned, we should generally expect this event to be called.
                AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
            }
            /// <summary>
            /// Loads references, set options and execute files specified in the initialization file.
            /// Also prints logo unless <paramref name="isRestarting"/> is true.
            /// </summary>
            private async Task<EvaluationState> InitializeContextAsync(
                Task<EvaluationState> lastTask,
                RemoteAsyncOperation<RemoteExecutionResult> operation,
                string initializationFileOpt,
                bool isRestarting)
            {
                Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));

                var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);

                try
                {
                    // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(_replServiceProvider.Logo);
                    }

                    if (File.Exists(initializationFileOpt))
                    {
                        Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt)));
                        var parser = _replServiceProvider.CommandLineParser;

                        // The base directory for relative paths is the directory that contains the .rsp file.
                        // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
                        var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
                        var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/);

                        foreach (var error in args.Errors)
                        {
                            var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
                            writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
                        }

                        if (args.Errors.Length == 0)
                        {
                            // TODO (tomat): other arguments
                            // TODO (tomat): parse options

                            var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);

                            _hostObject.ReferencePaths.Clear();
                            _hostObject.ReferencePaths.AddRange(args.ReferencePaths);

                            _hostObject.SourcePaths.Clear();

                            var metadataReferences = new List<PortableExecutableReference>();
                            foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
                            {
                                // interactive command line parser doesn't accept modules or linked assemblies
                                Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);

                                var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
                                if (!resolvedReferences.IsDefaultOrEmpty)
                                {
                                    metadataReferences.AddRange(resolvedReferences);
                                }
                            }

                            // only search for scripts next to the .rsp file:
                            var sourceSearchPaths = ImmutableArray<string>.Empty;

                            var rspState = new EvaluationState(
                                state.ScriptStateOpt,
                                state.ScriptOptions.AddReferences(metadataReferences),
                                sourceSearchPaths,
                                args.ReferencePaths,
                                rspDirectory);

                            foreach (CommandLineSourceFile file in args.SourceFiles)
                            {
                                // execute all files as scripts (matches csi/vbi semantics)

                                string fullPath = ResolveRelativePath(file.Path, rspDirectory, sourceSearchPaths, displayPath: true);
                                if (fullPath != null)
                                {
                                    var newScriptState = await ExecuteFileAsync(rspState, fullPath).ConfigureAwait(false);
                                    if (newScriptState != null)
                                    {
                                        rspState = rspState.WithScriptState(newScriptState);
                                    }
                                }
                            }

                            state = new EvaluationState(
                                rspState.ScriptStateOpt,
                                rspState.ScriptOptions,
                                ImmutableArray<string>.Empty,
                                args.ReferencePaths,
                                state.WorkingDirectory);
                        }
                    }

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation);
                    }
                }
                catch (Exception e)
                {
                    ReportUnhandledException(e);
                }
                finally
                {
                    state = CompleteExecution(state, operation, success: true);
                }

                return state;
            }
Exemplo n.º 7
0
            public int HandleMatch(IProcessorState processor, int bufferLength, ref int currentBufferPosition, int token, Stream target)
            {
                bool flag;

                if (processor.Config.Flags.TryGetValue(OperationName, out flag) && !flag)
                {
                    target.Write(Tokens[token].Value, Tokens[token].Start, Tokens[token].Length);
                    return(Tokens[token].Length);
                }

                // conditional has not started, or this is the "if"
                if (_current != null || IsTokenIndexOfType(token, IfTokenBaseIndex) || IsTokenIndexOfType(token, IfTokenActionableBaseIndex))
                {
                    if (_definition._wholeLine)
                    {
                        processor.SeekBackUntil(processor.EncodingConfig.LineEndings);
                    }
                    else if (_definition._trimWhitespace)
                    {
                        processor.TrimWhitespace(false, true, ref bufferLength, ref currentBufferPosition);
                    }
                }

BEGIN:
                //Got the "if" token...
                if (IsTokenIndexOfType(token, IfTokenBaseIndex) || IsTokenIndexOfType(token, IfTokenActionableBaseIndex))
                {
                    if (_current == null)
                    {
                        _current = new EvaluationState(this);
                    }
                    else
                    {
                        _pendingCompletion.Push(_current);
                        _current = new EvaluationState(this);
                    }

                    //If the "if" branch is taken, all else and elseif blocks will be omitted, return
                    //  control to the processor so nested "if"s/mutations can be processed. Note that
                    //  this block will not be terminated until the corresponding endif is found
                    if (_current.Evaluate(processor, ref bufferLength, ref currentBufferPosition))
                    {
                        if (_definition.WholeLine)
                        {
                            processor.SeekForwardThrough(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition);
                        }

                        if (IsTokenIndexOfType(token, IfTokenActionableBaseIndex))
                        {
                            // "Actionable" if token, so enable the flag operation(s)
                            _current.ToggleActionableOperations(true, processor);
                        }

                        // if (true_condition) was found.
                        return(0);
                    }
                    else
                    {
                        // if (false_condition) was found. Skip to the next token of the if-elseif-elseif-...elseif-else-endif
                        SeekToNextTokenAtSameLevel(processor, ref bufferLength, ref currentBufferPosition, out token);
                        goto BEGIN;
                    }
                }

                // If we've got an unbalanced statement, emit the token
                if (_current == null)
                {
                    target.Write(Tokens[token].Value, Tokens[token].Start, Tokens[token].Length);
                    return(Tokens[token].Length);
                }

                //Got the endif token, exit to the parent "if" scope if it exists
                if (IsTokenIndexOfType(token, EndTokenBaseIndex))
                {
                    if (_pendingCompletion.Count > 0)
                    {
                        _current = _pendingCompletion.Pop();
                        _current.ToggleActionableOperations(_current.ActionableOperationsEnabled, processor);
                    }
                    else
                    {
                        // disable the special case operations (note: they may already be disabled, but cheaper to do than check)
                        _current.ToggleActionableOperations(false, processor);
                        _current = null;
                    }

                    if (_definition._wholeLine)
                    {
                        processor.SeekForwardThrough(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition);
                    }
                    else if (_definition._trimWhitespace)
                    {
                        processor.TrimWhitespace(true, false, ref bufferLength, ref currentBufferPosition);
                    }

                    return(0);
                }

                if (_current.BranchTaken)
                {
                    processor.SeekBackUntil(processor.EncodingConfig.LineEndings, true);
                    //A previous branch was taken. Skip to the endif token.
                    // NOTE: this can probably use the new method SeekToNextTokenAtSameLevel() - they do almost the same thing.
                    SkipToMatchingEndif(processor, ref bufferLength, ref currentBufferPosition, ref token);

                    if (_pendingCompletion.Count > 0)
                    {
                        _current = _pendingCompletion.Pop();
                        _current.ToggleActionableOperations(_current.ActionableOperationsEnabled, processor);
                    }
                    else
                    {
                        // disable the special case operation (note: it may already be disabled, but cheaper to do than check)
                        _current.ToggleActionableOperations(false, processor);
                        _current = null;
                    }

                    if (_definition._wholeLine)
                    {
                        processor.SeekForwardUntil(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition);
                    }
                    else if (_definition._trimWhitespace)
                    {
                        processor.TrimWhitespace(true, false, ref bufferLength, ref currentBufferPosition);
                    }

                    return(0);
                }

                //We have an "elseif" and haven't taken a previous branch
                if (IsTokenIndexOfType(token, ElseIfTokenBaseIndex) || IsTokenIndexOfType(token, ElseIfTokenActionableBaseIndex))
                {
                    // 8-19 attempt to make the same as if() handling
                    //
                    if (_current.Evaluate(processor, ref bufferLength, ref currentBufferPosition))
                    {
                        if (_definition.WholeLine)
                        {
                            processor.SeekForwardThrough(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition);
                        }

                        if (IsTokenIndexOfType(token, ElseIfTokenActionableBaseIndex))
                        {
                            // the elseif branch is taken.
                            _current.ToggleActionableOperations(true, processor);
                        }

                        return(0);
                    }
                    else
                    {
                        SeekToNextTokenAtSameLevel(processor, ref bufferLength, ref currentBufferPosition, out token);

                        // In the original version this was conditional on SeekToToken() succeeding.
                        // Not sure if it should be conditional. It should never fail, unless the template is malformed.
                        goto BEGIN;
                    }
                }

                //We have an "else" token and haven't taken any other branches, return control
                //  after setting that a branch has been taken
                if (IsTokenIndexOfType(token, ElseTokenBaseIndex) || IsTokenIndexOfType(token, ElseTokenActionableBaseIndex))
                {
                    if (IsTokenIndexOfType(token, ElseTokenActionableBaseIndex))
                    {
                        _current.ToggleActionableOperations(true, processor);
                    }

                    _current.BranchTaken = true;
                    processor.WhitespaceHandler(ref bufferLength, ref currentBufferPosition, wholeLine: _definition._wholeLine, trim: _definition._trimWhitespace);
                    return(0);
                }
                else
                {
                    Debug.Assert(true, "Unknown token index: " + token);
                    return(0);   // TODO: revisit. Not sure what's best here.
                }
            }
Exemplo n.º 8
0
        protected void EvaluateExpressionResult()
        {
            // We're going to customize the unexpanded display string, as well as the expanded
            // view (if requested later).

            // @TODO: Really don't understand why, but when we invoke the default eval below, and we get
            // reentrant calls for child member UObjects, they are coming back as root expressions
            // with an empty FullName. This subsequently fails to evaluate if we pass it through to
            // default eval again. Perhaps this is somehow related to breaking the potential infinite
            // recursion of visualizing children in order to visualize the parent, but don't follow how it
            // it supposed to be dealt with.
            if (expression_.TagValue == DkmVisualizedExpression.Tag.RootVisualizedExpression)
            {
                var as_root = expression_ as DkmRootVisualizedExpression;
                if (as_root.FullName.Length == 0)
                {
                    string display_str = "{...}";
                    eval_ = DkmSuccessEvaluationResult.Create(
                        expression_.InspectionContext,
                        expression_.StackFrame,
                        as_root.Name,
                        as_root.Name,
                        DkmEvaluationResultFlags.ReadOnly,
                        display_str,
                        "",
#if !VS2013
                        as_root.Type,
#else
                        "Unknown",
#endif
                        DkmEvaluationResultCategory.Other,
                        DkmEvaluationResultAccessType.None,
                        DkmEvaluationResultStorageType.None,
                        DkmEvaluationResultTypeModifierFlags.None,
                        null,
                        null,
                        null,
                        null
                        );
                    state_ = EvaluationState.MinimalEvaluation;
                    return;
                }
            }
            //

            string custom_display_str             = Resources.UE4PropVis.IDS_DISP_CONDENSED;
            DkmSuccessEvaluationResult proto_eval = null;
            bool   is_pointer;
            bool   is_null;
            string address_str = "";

            // @NOTE: Initially here we were executing the full default evaluation of our expression.
            // Problem is that this will call back into us for all UObject children of the expression,
            // because it needs to generate a visualization for them in order to construct its {member vals...} display string.
            // And then, we just ignore that anyway and display our own...

            // The following attempts to avoid that by casting our expression to void* and then evaluating that.
            // If it fails, we assume we are non-pointer. If it succeeds, we can determine from the result whether we are null or not.

            // @WARNING: This may not be so safe, since we can't determine whether evaluation failed because we tried to cast a non-pointer
            // to void*, or because the passed in expression was not valid in the first place. Believe we should be okay, since we should
            // only be receiving expressions that have already been determined to be suitable for our custom visualizer.

            // Ideally though, we'd be able to get a raw expression evaluation, without any visualization taking place.
            // Seems there must be a way to do this, but looks like it requires using a different API...
            const bool UseVoidCastOptimization = true;

            string default_expr_str = Utility.GetExpressionFullName(expression_);
            if (UseVoidCastOptimization)
            {
                default_expr_str = ExpressionManipulator.FromExpression(default_expr_str).PtrCast(Cpp.Void).Expression;
            }

            DkmEvaluationResult eval = DefaultEE.DefaultEval(default_expr_str, expression_, true);

            if (!UseVoidCastOptimization)
            {
                if (eval.TagValue != DkmEvaluationResult.Tag.SuccessResult)
                {
                    // Genuine failure to evaluate the passed in expression
                    eval_  = eval;
                    state_ = EvaluationState.Failed;
                    return;
                }
                else
                {
                    proto_eval         = (DkmSuccessEvaluationResult)eval;
                    custom_display_str = proto_eval.Value;

                    is_pointer = IsPointer(proto_eval);
                    is_null    = is_pointer && IsPointerNull(proto_eval);
                    // @TODO: need to extract address string
                }
            }
            else
            {
                DkmDataAddress address = null;
                if (eval.TagValue != DkmEvaluationResult.Tag.SuccessResult)
                {
                    // Assume the failure just implies the expression was non-pointer (thereby assuming that it was itself valid!)

                    // @TODO: Could actually fall back onto standard evaluation here, in order to determine for sure
                    // that the original expression is valid. Failure wouldn't be common since most of the time we are
                    // dealing with pointer expressions, so any potential optimization should still be gained.

                    is_pointer = false;
                    is_null    = false;
                }
                else
                {
                    var success = (DkmSuccessEvaluationResult)eval;
                    Debug.Assert(IsPointer(success));
                    is_pointer  = true;
                    is_null     = is_pointer && IsPointerNull(success);
                    address     = success.Address;
                    address_str = success.Value;
                }

                proto_eval = DkmSuccessEvaluationResult.Create(
                    expression_.InspectionContext,
                    expression_.StackFrame,
                    "",
                    "",
                    DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable,
                    "",
                    "",
#if !VS2013
                    Utility.GetExpressionType(expression_),
#else
                    is_pointer ? "UObject *" : "UObject",
#endif
                    DkmEvaluationResultCategory.Other,
                    DkmEvaluationResultAccessType.None,
                    DkmEvaluationResultStorageType.None,
                    DkmEvaluationResultTypeModifierFlags.None,
                    address,
                    null,
                    null,
                    null
                    );
            }

            string obj_expression_str = Utility.GetExpressionFullName(expression_);
            var    obj_em             = ExpressionManipulator.FromExpression(obj_expression_str);

            // Store pointer flags on the expression
            expression_.SetDataItem(
                DkmDataCreationDisposition.CreateAlways,
                new UObjectDataItem(is_pointer, is_null)
                );

            if (!is_pointer)
            {
                // All subsequent manipulations of the expression assume it starts as a pointer to a
                // UObject-derived class, so if our expression is to a dereferenced UObject, just
                // prefix an 'address of' to the expression string.
                obj_em = obj_em.AddressOf();
            }

            // Generate the condensed display string.
            if (is_null)
            {
                if (Config.CustomNullObjectPreview)
                {
                    custom_display_str = "<NULL> UObject";
                }
                else
                {
                    var null_eval = DefaultEE.DefaultEval("(void*)0", expression_, true) as DkmSuccessEvaluationResult;
                    custom_display_str = null_eval.Value + " <NULL>";
                }
            }
            else if (Config.DisplayUObjectPreview)
            {
                // Prefix the address, if this is a pointer expression
                string address_prefix_str = "";
                if (is_pointer)
                {
                    address_prefix_str = address_str + " ";
                }

                // Specialized display for UClass?
                bool uclass_specialized = false;
                if (Config.DisplaySpecializedUClassPreview)
                {
                    var    uclass_em = obj_em.PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjClass);
                    var    _uclass_fname_expr_str = uclass_em.PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjName).Expression;
                    string _obj_uclass_name_str   = UE4Utility.GetFNameAsString(_uclass_fname_expr_str, expression_);
                    // @TODO: To simplify and for performance reasons, just hard coding known UClass variants
                    if (_obj_uclass_name_str == "Class" ||
                        _obj_uclass_name_str == "BlueprintGeneratedClass" ||
                        _obj_uclass_name_str == "WidgetBlueprintGeneratedClass")
                    {
                        var    fname_expr_str = obj_em.PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjName).Expression;
                        string obj_name_str   = UE4Utility.GetFNameAsString(fname_expr_str, expression_);

                        var parent_uclass_fname_expr_str = obj_em.PtrCast(Typ.UStruct).PtrMember(Memb.SuperStruct).PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjName).Expression;
                        // This will return null if lookup failed for any reason.
                        // We'll assume this meant no super class exists (ie. we're dealing with UClass itself)
                        string parent_uclass_name_str = UE4Utility.GetFNameAsString(parent_uclass_fname_expr_str, expression_);
                        if (parent_uclass_name_str == null)
                        {
                            parent_uclass_name_str = "None";
                        }

                        custom_display_str = String.Format(
                            "{0}{{ClassName='{1}', Parent='{2}'}}",
                            address_prefix_str,
                            obj_name_str,
                            parent_uclass_name_str
                            );
                        uclass_specialized = true;
                    }
                }

                if (!uclass_specialized)
                {
                    // For standard UObject condensed display string, show the object FName and its UClass.
                    // @TODO: The evaluations required for this may be a performance issue, since they'll be done for all UObject children of any default visualized
                    // aggregate type, even when it is not expanded (the default behaviour is to create a {...} display list of child member visualizations).
                    var    fname_expr_str = obj_em.PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjName).Expression;
                    string obj_name_str   = UE4Utility.GetFNameAsString(fname_expr_str, expression_);

                    var    uclass_fname_expr_str = obj_em.PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjClass).PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjName).Expression;
                    string obj_uclass_name_str   = UE4Utility.GetFNameAsString(uclass_fname_expr_str, expression_);

                    custom_display_str = String.Format(
                        "{0}{{Name='{1}', Class='{2}'}}",
                        address_prefix_str,
                        obj_name_str,
                        obj_uclass_name_str
                        );
                }
            }

            eval_ = DkmSuccessEvaluationResult.Create(
                proto_eval.InspectionContext,
                proto_eval.StackFrame,
                // Override the eval name with the original expression name, since it will
                // have inherited the ",!" suffix.
                Utility.GetExpressionName(expression_),
                Utility.GetExpressionFullName(expression_),
                proto_eval.Flags,
                custom_display_str,                //success_eval.Value,
                proto_eval.EditableValue,
                proto_eval.Type,
                proto_eval.Category,
                proto_eval.Access,
                proto_eval.StorageType,
                proto_eval.TypeModifierFlags,
                proto_eval.Address,
                proto_eval.CustomUIVisualizers,
                proto_eval.ExternalModules,
                null
                );
            state_ = EvaluationState.Evaluated;
        }
Exemplo n.º 9
0
 public EvaluationResult Evaluate(EvaluationState state, ReadOnlyList <IEvaluate> args, ReadOnlyList <Object> data)
 {
     return(new EvaluationResult());
 }
Exemplo n.º 10
0
        public EvaluationResult Evaluate(EvaluationState state, ReadOnlyList <IEvaluate> args, ReadOnlyList <Object> data)
        {
            Combat.Character character = state.Character as Combat.Character;
            if (character == null)
            {
                return(new EvaluationResult());
            }

            EvaluationResult result = args[1].Evaluate(state);

            if (result.ResultType == ResultType.None)
            {
                return(new EvaluationResult());
            }

            FuncCaller varcaller = args[0] as FuncCaller;

            if (varcaller == null)
            {
                return(new EvaluationResult());
            }

            if (varcaller.Function is Triggers.Var)
            {
                EvaluationResult varindex = varcaller.Args[0].Evaluate(state);
                if (varindex.ResultType == ResultType.None)
                {
                    return(new EvaluationResult());
                }

                if (character.Variables.SetInterger(varindex.IntValue, false, result.IntValue) == false)
                {
                    return(new EvaluationResult());
                }
            }
            else if (varcaller.Function is Triggers.FVar)
            {
                EvaluationResult varindex = varcaller.Args[0].Evaluate(state);
                if (varindex.ResultType == ResultType.None)
                {
                    return(new EvaluationResult());
                }

                if (character.Variables.SetFloat(varindex.IntValue, false, result.FloatValue) == false)
                {
                    return(new EvaluationResult());
                }
            }
            else if (varcaller.Function is Triggers.SysVar)
            {
                EvaluationResult varindex = varcaller.Args[0].Evaluate(state);
                if (varindex.ResultType == ResultType.None)
                {
                    return(new EvaluationResult());
                }

                if (character.Variables.SetInterger(varindex.IntValue, true, result.IntValue) == false)
                {
                    return(new EvaluationResult());
                }
            }
            else if (varcaller.Function is Triggers.SysFVar)
            {
                EvaluationResult varindex = varcaller.Args[0].Evaluate(state);
                if (varindex.ResultType == ResultType.None)
                {
                    return(new EvaluationResult());
                }

                if (character.Variables.SetFloat(varindex.IntValue, true, result.FloatValue) == false)
                {
                    return(new EvaluationResult());
                }
            }
            else
            {
                return(new EvaluationResult());
            }

            return(result);
        }
Exemplo n.º 11
0
        //////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////
        public IEnumerable<E> getSuccessors(EvaluationState es)
        {

        }
Exemplo n.º 12
0
		protected void EvaluateExpressionResult()
		{
			// We're going to customize the unexpanded display string, as well as the expanded
			// view (if requested later).

			// @TODO: Really don't understand why, but when we invoke the default eval below, and we get 
			// reentrant calls for child member UObjects, they are coming back as root expressions
			// with an empty FullName. This subsequently fails to evaluate if we pass it through to 
			// default eval again. Perhaps this is somehow related to breaking the potential infinite
			// recursion of visualizing children in order to visualize the parent, but don't follow how it
			// it supposed to be dealt with.
			if (expression_.TagValue == DkmVisualizedExpression.Tag.RootVisualizedExpression)
			{
				var as_root = expression_ as DkmRootVisualizedExpression;
				if (as_root.FullName.Length == 0)
				{
					string display_str = "{...}";
					eval_ = DkmSuccessEvaluationResult.Create(
						expression_.InspectionContext,
						expression_.StackFrame,
						as_root.Name,
						as_root.Name,
						DkmEvaluationResultFlags.ReadOnly,
						display_str,
						"",
#if !VS2013
						as_root.Type,
#else
						"Unknown",
#endif
						DkmEvaluationResultCategory.Other,
						DkmEvaluationResultAccessType.None,
						DkmEvaluationResultStorageType.None,
						DkmEvaluationResultTypeModifierFlags.None,
						null,
						null,
						null,
						null
						);
					state_ = EvaluationState.MinimalEvaluation;
					return;
				}
			}
			//

			string custom_display_str = Resources.UE4PropVis.IDS_DISP_CONDENSED;
			DkmSuccessEvaluationResult proto_eval = null;
			bool is_pointer;
			bool is_null;
			string address_str = "";

			// @NOTE: Initially here we were executing the full default evaluation of our expression.
			// Problem is that this will call back into us for all UObject children of the expression,
			// because it needs to generate a visualization for them in order to construct its {member vals...} display string.
			// And then, we just ignore that anyway and display our own...

			// The following attempts to avoid that by casting our expression to void* and then evaluating that.
			// If it fails, we assume we are non-pointer. If it succeeds, we can determine from the result whether we are null or not.
			
			// @WARNING: This may not be so safe, since we can't determine whether evaluation failed because we tried to cast a non-pointer
			// to void*, or because the passed in expression was not valid in the first place. Believe we should be okay, since we should
			// only be receiving expressions that have already been determined to be suitable for our custom visualizer.

			// Ideally though, we'd be able to get a raw expression evaluation, without any visualization taking place.
			// Seems there must be a way to do this, but looks like it requires using a different API...
			const bool UseVoidCastOptimization = true;

			string default_expr_str = Utility.GetExpressionFullName(expression_);
			if(UseVoidCastOptimization)
			{
				default_expr_str = ExpressionManipulator.FromExpression(default_expr_str).PtrCast(Cpp.Void).Expression;
			}

			DkmEvaluationResult eval = DefaultEE.DefaultEval(default_expr_str, expression_, true);

			if (!UseVoidCastOptimization)
			{
				if (eval.TagValue != DkmEvaluationResult.Tag.SuccessResult)
				{
					// Genuine failure to evaluate the passed in expression
					eval_ = eval;
					state_ = EvaluationState.Failed;
					return;
				}
				else
				{
					proto_eval = (DkmSuccessEvaluationResult)eval;
					custom_display_str = proto_eval.Value;

					is_pointer = IsPointer(proto_eval);
					is_null = is_pointer && IsPointerNull(proto_eval);
					// @TODO: need to extract address string
				}
			}
			else
			{
				DkmDataAddress address = null;
				if (eval.TagValue != DkmEvaluationResult.Tag.SuccessResult)
				{
					// Assume the failure just implies the expression was non-pointer (thereby assuming that it was itself valid!)
					
					// @TODO: Could actually fall back onto standard evaluation here, in order to determine for sure
					// that the original expression is valid. Failure wouldn't be common since most of the time we are
					// dealing with pointer expressions, so any potential optimization should still be gained.

					is_pointer = false;
					is_null = false;
				}
				else
				{
					var success = (DkmSuccessEvaluationResult)eval;
                    Debug.Assert(IsPointer(success));
					is_pointer = true;
					is_null = is_pointer && IsPointerNull(success);
					address = success.Address;
					address_str = success.Value;
				}

				proto_eval = DkmSuccessEvaluationResult.Create(
						expression_.InspectionContext,
						expression_.StackFrame,
						"",
						"",
						DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable,
						"",
						"",
#if !VS2013
						Utility.GetExpressionType(expression_),
#else
						is_pointer ? "UObject *" : "UObject",
#endif
						DkmEvaluationResultCategory.Other,
						DkmEvaluationResultAccessType.None,
						DkmEvaluationResultStorageType.None,
						DkmEvaluationResultTypeModifierFlags.None,
						address,
						null,
						null,
						null
						);
			}

			string obj_expression_str = Utility.GetExpressionFullName(expression_);
			var obj_em = ExpressionManipulator.FromExpression(obj_expression_str);

			// Store pointer flags on the expression
			expression_.SetDataItem(
				DkmDataCreationDisposition.CreateAlways,
				new UObjectDataItem(is_pointer, is_null)
				);

			if (!is_pointer)
			{
				// All subsequent manipulations of the expression assume it starts as a pointer to a 
				// UObject-derived class, so if our expression is to a dereferenced UObject, just 
				// prefix an 'address of' to the expression string.
				obj_em = obj_em.AddressOf();
			}

			// Generate the condensed display string.
			if (is_null)
			{
				if (Config.CustomNullObjectPreview)
				{
					custom_display_str = "<NULL> UObject";
				}
				else
				{
					var null_eval = DefaultEE.DefaultEval("(void*)0", expression_, true) as DkmSuccessEvaluationResult;
					custom_display_str = null_eval.Value + " <NULL>";
				}
			}
			else if (Config.DisplayUObjectPreview)
			{
				// Prefix the address, if this is a pointer expression
				string address_prefix_str = "";
				if(is_pointer)
				{
					address_prefix_str = address_str + " ";
				}

				// Specialized display for UClass?
				bool uclass_specialized = false;
				if (Config.DisplaySpecializedUClassPreview)
				{
					var uclass_em = obj_em.PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjClass);
					var _uclass_fname_expr_str = uclass_em.PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjName).Expression;
					string _obj_uclass_name_str = UE4Utility.GetFNameAsString(_uclass_fname_expr_str, expression_);
					// @TODO: To simplify and for performance reasons, just hard coding known UClass variants
					if (_obj_uclass_name_str == "Class" ||
						_obj_uclass_name_str == "BlueprintGeneratedClass" ||
						_obj_uclass_name_str == "WidgetBlueprintGeneratedClass")
					{
						var fname_expr_str = obj_em.PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjName).Expression;
						string obj_name_str = UE4Utility.GetFNameAsString(fname_expr_str, expression_);

						var parent_uclass_fname_expr_str = obj_em.PtrCast(Typ.UStruct).PtrMember(Memb.SuperStruct).PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjName).Expression;
						// This will return null if lookup failed for any reason.
						// We'll assume this meant no super class exists (ie. we're dealing with UClass itself)
						string parent_uclass_name_str = UE4Utility.GetFNameAsString(parent_uclass_fname_expr_str, expression_);
						if (parent_uclass_name_str == null)
						{
							parent_uclass_name_str = "None";
						}

						custom_display_str = String.Format(
							"{0}{{ClassName='{1}', Parent='{2}'}}",
							address_prefix_str,
							obj_name_str,
							parent_uclass_name_str
							);
						uclass_specialized = true;
					}
				}

				if (!uclass_specialized)
				{
					// For standard UObject condensed display string, show the object FName and its UClass.
					// @TODO: The evaluations required for this may be a performance issue, since they'll be done for all UObject children of any default visualized
					// aggregate type, even when it is not expanded (the default behaviour is to create a {...} display list of child member visualizations).
					var fname_expr_str = obj_em.PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjName).Expression;
					string obj_name_str = UE4Utility.GetFNameAsString(fname_expr_str, expression_);

					var uclass_fname_expr_str = obj_em.PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjClass).PtrCast(Typ.UObjectBase).PtrMember(Memb.ObjName).Expression;
					string obj_uclass_name_str = UE4Utility.GetFNameAsString(uclass_fname_expr_str, expression_);

					custom_display_str = String.Format(
						"{0}{{Name='{1}', Class='{2}'}}",
						address_prefix_str,
						obj_name_str,
						obj_uclass_name_str
						);
				}
			}

			eval_ = DkmSuccessEvaluationResult.Create(
				proto_eval.InspectionContext,
				proto_eval.StackFrame,
				// Override the eval name with the original expression name, since it will
				// have inherited the ",!" suffix.
				Utility.GetExpressionName(expression_),
				Utility.GetExpressionFullName(expression_),
				proto_eval.Flags,
				custom_display_str,//success_eval.Value,
				proto_eval.EditableValue,
				proto_eval.Type,
				proto_eval.Category,
				proto_eval.Access,
				proto_eval.StorageType,
				proto_eval.TypeModifierFlags,
				proto_eval.Address,
				proto_eval.CustomUIVisualizers,
				proto_eval.ExternalModules,
				null
				);
			state_ = EvaluationState.Evaluated;
		}
Exemplo n.º 13
0
 public void RaiseNewError(String message, ScriptObject location)
 {
     errorObject     = new GenericScriptObject("message", message, "location", location, "stack-trace", new ScriptList());
     evaluationState = EvaluationState.UnwindingError;
 }
Exemplo n.º 14
0
 public Object UnBreak()
 {
     System.Diagnostics.Debug.Assert(evaluationState == EvaluationState.UnwindingBreak);
     evaluationState = EvaluationState.Normal;
     return(breakObject);
 }
Exemplo n.º 15
0
 public TetrisActionWithEvaluation(TetrisAction action, EvaluationState evaluationState)
 {
     Action          = action;
     EvaluationState = evaluationState;
 }
Exemplo n.º 16
0
 public void RaiseNewError(String message, ScriptObject location)
 {
     errorObject = new GenericScriptObject("message", message, "location", location, "stack-trace", new ScriptList());
     evaluationState = EvaluationState.UnwindingError;
 }
Exemplo n.º 17
0
 public Object UnBreak()
 {
     System.Diagnostics.Debug.Assert(evaluationState == EvaluationState.UnwindingBreak);
     evaluationState = EvaluationState.Normal;
     return breakObject;
 }
Exemplo n.º 18
0
 public override void Evaluate <T>(
     ICircuitEvaluator <T> evaluator,
     EvaluationState <T> evaluationState)
 {
     evaluationState.SetGateEvaluationValue(this, evaluationState.GetInput(_inputIndex));
 }
Exemplo n.º 19
0
		public EvaluationResult Evaluate(EvaluationState state, ReadOnlyList<IEvaluate> args, ReadOnlyList<Object> data)
		{
			return new EvaluationResult();
		}
Exemplo n.º 20
0
 public EvaluationResult Evaluate(EvaluationState state, ReadOnlyList <IEvaluate> args, ReadOnlyList <Object> data)
 {
     return(BaseOperations.LogicalNot(args[0].Evaluate(state)));
 }
Exemplo n.º 21
0
            /// <summary>
            /// Loads references, set options and execute files specified in the initialization file.
            /// Also prints logo unless <paramref name="isRestarting"/> is true.
            /// </summary>
            private async Task <EvaluationState> InitializeContextAsync(
                Task <EvaluationState> lastTask,
                RemoteAsyncOperation <RemoteExecutionResult> operation,
                string initializationFileOpt,
                bool isRestarting)
            {
                Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));

                var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);

                try
                {
                    // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(_replServiceProvider.Logo);
                    }

                    if (File.Exists(initializationFileOpt))
                    {
                        Console.Out.WriteLine(string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(initializationFileOpt)));
                        var parser = _replServiceProvider.CommandLineParser;

                        // The base directory for relative paths is the directory that contains the .rsp file.
                        // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
                        var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
                        var args         = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null);

                        foreach (var error in args.Errors)
                        {
                            var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
                            writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
                        }

                        if (args.Errors.Length == 0)
                        {
                            var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);
                            var sourceResolver   = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory);

                            var metadataReferences = new List <PortableExecutableReference>();
                            foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
                            {
                                // interactive command line parser doesn't accept modules or linked assemblies
                                Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);

                                var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
                                if (!resolvedReferences.IsDefaultOrEmpty)
                                {
                                    metadataReferences.AddRange(resolvedReferences);
                                }
                            }

                            var scriptPathOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path;

                            var rspState = new EvaluationState(
                                state.ScriptStateOpt,
                                state.ScriptOptions.
                                WithFilePath(scriptPathOpt).
                                WithReferences(metadataReferences).
                                WithImports(CommandLineHelpers.GetImports(args)).
                                WithMetadataResolver(metadataResolver).
                                WithSourceResolver(sourceResolver),
                                args.SourcePaths,
                                args.ReferencePaths,
                                rspDirectory);

                            _globals.ReferencePaths.Clear();
                            _globals.ReferencePaths.AddRange(args.ReferencePaths);

                            _globals.SourcePaths.Clear();
                            _globals.SourcePaths.AddRange(args.SourcePaths);

                            _globals.Args.AddRange(args.ScriptArguments);

                            if (scriptPathOpt != null)
                            {
                                var newScriptState = await TryExecuteFileAsync(rspState, scriptPathOpt).ConfigureAwait(false);

                                if (newScriptState != null)
                                {
                                    // remove references and imports from the options, they have been applied and will be inherited from now on:
                                    rspState = rspState.
                                               WithScriptState(newScriptState).
                                               WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences());
                                }
                            }

                            state = rspState;
                        }
                    }

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(InteractiveHostResources.Type_Sharphelp_for_more_information);
                    }
                }
                catch (Exception e)
                {
                    ReportUnhandledException(e);
                }
                finally
                {
                    state = CompleteExecution(state, operation, success: true);
                }

                return(state);
            }
Exemplo n.º 22
0
            /// <summary>
            /// Loads references, set options and execute files specified in the initialization file.
            /// Also prints logo unless <paramref name="isRestarting"/> is true.
            /// </summary>
            private async Task <EvaluationState> InitializeContextAsync(
                Task <EvaluationState> lastTask,
                RemoteAsyncOperation <RemoteExecutionResult> operation,
                string initializationFileOpt,
                bool isRestarting)
            {
                Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));

                var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);

                try
                {
                    // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(_replServiceProvider.Logo);
                    }

                    if (File.Exists(initializationFileOpt))
                    {
                        Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt)));
                        var parser = _replServiceProvider.CommandLineParser;

                        // The base directory for relative paths is the directory that contains the .rsp file.
                        // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
                        var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
                        var args         = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/);

                        foreach (var error in args.Errors)
                        {
                            var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
                            writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
                        }

                        if (args.Errors.Length == 0)
                        {
                            // TODO (tomat): other arguments
                            // TODO (tomat): parse options

                            var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);

                            _hostObject.ReferencePaths.Clear();
                            _hostObject.ReferencePaths.AddRange(args.ReferencePaths);

                            _hostObject.SourcePaths.Clear();

                            var metadataReferences = new List <PortableExecutableReference>();
                            foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
                            {
                                // interactive command line parser doesn't accept modules or linked assemblies
                                Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);

                                var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
                                if (!resolvedReferences.IsDefaultOrEmpty)
                                {
                                    metadataReferences.AddRange(resolvedReferences);
                                }
                            }

                            // only search for scripts next to the .rsp file:
                            var sourceSearchPaths = ImmutableArray <string> .Empty;

                            var rspState = new EvaluationState(
                                state.ScriptStateOpt,
                                state.ScriptOptions.AddReferences(metadataReferences),
                                sourceSearchPaths,
                                args.ReferencePaths,
                                rspDirectory);

                            foreach (CommandLineSourceFile file in args.SourceFiles)
                            {
                                // execute all files as scripts (matches csi/vbi semantics)

                                string fullPath = ResolveRelativePath(file.Path, rspDirectory, sourceSearchPaths, displayPath: true);
                                if (fullPath != null)
                                {
                                    var newScriptState = await ExecuteFileAsync(rspState, fullPath).ConfigureAwait(false);

                                    if (newScriptState != null)
                                    {
                                        rspState = rspState.WithScriptState(newScriptState);
                                    }
                                }
                            }

                            state = new EvaluationState(
                                rspState.ScriptStateOpt,
                                rspState.ScriptOptions,
                                ImmutableArray <string> .Empty,
                                args.ReferencePaths,
                                state.WorkingDirectory);
                        }
                    }

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation);
                    }
                }
                catch (Exception e)
                {
                    ReportUnhandledException(e);
                }
                finally
                {
                    state = CompleteExecution(state, operation, success: true);
                }

                return(state);
            }
Exemplo n.º 23
0
 public EvaluationResult Evaluate(EvaluationState state, ReadOnlyList <IEvaluate> args, ReadOnlyList <Object> data)
 {
     return(BaseOperations.BitXor(args[0].Evaluate(state), args[1].Evaluate(state)));
 }
Exemplo n.º 24
0
            private async Task <EvaluationState> InitializeContextAsync(
                Task <EvaluationState> lastTask,
                TaskCompletionSource <RemoteExecutionResult> completionSource,
                string?initializationFilePath,
                bool isRestarting)
            {
                Contract.ThrowIfFalse(initializationFilePath == null || PathUtilities.IsAbsolute(initializationFilePath));
                var serviceState = GetServiceState();
                var state        = await ReportUnhandledExceptionIfAnyAsync(lastTask).ConfigureAwait(false);

                string?initializationScriptPath = null;
                var    initialImports           = ImmutableArray <string> .Empty;
                var    metadataReferencePaths   = ImmutableArray.CreateBuilder <string>();

                try
                {
                    metadataReferencePaths.Add(typeof(object).Assembly.Location);
                    metadataReferencePaths.Add(typeof(InteractiveScriptGlobals).Assembly.Location);

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(serviceState.ReplServiceProvider.Logo);
                    }

                    if (File.Exists(initializationFilePath))
                    {
                        Console.Out.WriteLine(string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(initializationFilePath)));
                        var parser = serviceState.ReplServiceProvider.CommandLineParser;

                        // Add the Framework runtime directory to reference search paths when running on .NET Framework (PlatformAssemblyPaths list is empty).
                        // Otherwise, platform assemblies are looked up in PlatformAssemblyPaths directly.
                        var sdkDirectory = s_currentPlatformInfo.PlatformAssemblyPaths.IsEmpty ? RuntimeEnvironment.GetRuntimeDirectory() : null;

                        var rspDirectory = Path.GetDirectoryName(initializationFilePath);
                        var args         = parser.Parse(new[] { "@" + initializationFilePath }, baseDirectory: rspDirectory, sdkDirectory, additionalReferenceDirectories: null);

                        foreach (var error in args.Errors)
                        {
                            var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
                            writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
                        }

                        if (args.Errors.Length == 0)
                        {
                            var referencePaths = args.ReferencePaths;
                            var sourcePaths    = args.SourcePaths;

                            // TODO: Workaround for https://github.com/dotnet/roslyn/issues/45346
                            var referencePathsWithoutRspDir = referencePaths.Remove(rspDirectory);
                            var metadataResolver            = state.MetadataReferenceResolver.WithSearchPaths(referencePathsWithoutRspDir);
                            var rspMetadataResolver         = state.MetadataReferenceResolver.WithSearchPaths(referencePaths).WithBaseDirectory(rspDirectory);

                            var sourceResolver = CreateSourceReferenceResolver(sourcePaths, rspDirectory);

                            var metadataReferences = new List <PortableExecutableReference>();
                            foreach (var cmdLineReference in args.MetadataReferences)
                            {
                                // interactive command line parser doesn't accept modules or linked assemblies
                                Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);

                                var resolvedReferences = rspMetadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
                                if (!resolvedReferences.IsDefaultOrEmpty)
                                {
                                    metadataReferences.AddRange(resolvedReferences);
                                    metadataReferencePaths.AddRange(resolvedReferences.Where(r => r.FilePath != null).Select(r => r.FilePath !));
                                }
                            }

                            initializationScriptPath = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path;
                            initialImports           = CommandLineHelpers.GetImports(args);

                            var rspState = new EvaluationState(
                                state.ScriptState,
                                state.ScriptOptions.
                                WithFilePath(initializationScriptPath).
                                WithReferences(metadataReferences).
                                WithImports(initialImports).
                                WithMetadataResolver(metadataResolver).
                                WithSourceResolver(sourceResolver),
                                args.SourcePaths,
                                rspDirectory);

                            var globals = serviceState.Globals;
                            globals.ReferencePaths.Clear();
                            globals.ReferencePaths.AddRange(referencePathsWithoutRspDir);

                            globals.SourcePaths.Clear();
                            globals.SourcePaths.AddRange(sourcePaths);

                            globals.Args.AddRange(args.ScriptArguments);

                            if (initializationScriptPath != null)
                            {
                                var newScriptState = await TryExecuteFileAsync(rspState, initializationScriptPath).ConfigureAwait(false);

                                if (newScriptState != null)
                                {
                                    // remove references and imports from the options, they have been applied and will be inherited from now on:
                                    rspState = rspState.
                                               WithScriptState(newScriptState).
                                               WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences());
                                }
                            }

                            state = rspState;
                        }
                    }

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(InteractiveHostResources.Type_Sharphelp_for_more_information);
                    }
                }
                catch (Exception e)
                {
                    ReportUnhandledException(e);
                }
                finally
                {
                    var initResult = new RemoteInitializationResult(initializationScriptPath, metadataReferencePaths.ToImmutableArray(), initialImports);
                    state = CompleteExecution(state, completionSource, success: true, initResult);
                }

                return(state);
            }
            public Service()
            {
                // TODO (tomat): we should share the copied files with the host
                _metadataFileProvider = new MetadataShadowCopyProvider(
                    Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"),
                    noShadowCopyDirectories: s_systemNoShadowCopyDirectories);

                _assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider);

                _formattingOptions = new ObjectFormattingOptions(
                    memberFormat: MemberDisplayFormat.Inline,
                    quoteStrings: true,
                    useHexadecimalNumbers: false,
                    maxOutputLength: 200,
                    memberIndentation: "  ");

                _hostObject = new InteractiveHostObject();

                var initialState = new EvaluationState(
                    scriptState: null,
                    scriptOptions: ScriptOptions.Default,
                    sourceSearchPaths: ImmutableArray<string>.Empty,
                    referenceSearchPaths: ImmutableArray<string>.Empty,
                    workingDirectory: Directory.GetCurrentDirectory());

                _lastTask = Task.FromResult(initialState);

                Console.OutputEncoding = Encoding.UTF8;
              
                // We want to be sure to delete the shadow-copied files when the process goes away. Frankly
                // there's nothing we can do if the process is forcefully quit or goes down in a completely
                // uncontrolled manner (like a stack overflow). When the process goes down in a controlled
                // manned, we should generally expect this event to be called.
                AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
            }
            public int HandleMatch(IProcessorState processor, int bufferLength, ref int currentBufferPosition, int token, Stream target)
            {
                bool flag;

                if (processor.Config.Flags.TryGetValue("conditionals", out flag) && !flag)
                {
                    byte[] tokenValue = Tokens[token];
                    target.Write(tokenValue, 0, tokenValue.Length);
                    return(tokenValue.Length);
                }

                if (_current != null || token == 0)
                {
                    if (_definition._wholeLine)
                    {
                        processor.SeekBackUntil(processor.EncodingConfig.LineEndings);
                    }
                    else if (_definition._trimWhitespace)
                    {
                        processor.TrimWhitespace(false, true, ref bufferLength, ref currentBufferPosition);
                    }
                }

BEGIN:
                //Got the "if" token...
                if (token == 0)
                {
                    if (_current == null)
                    {
                        _current = new EvaluationState(this);
                    }
                    else
                    {
                        _pendingCompletion.Push(_current);
                        _current = new EvaluationState(this);
                    }

                    //If the "if" branch is taken, all else and elseif blocks will be omitted, return
                    //  control to the processor so nested "if"s/mutations can be processed. Note that
                    //  this block will not be terminated until the corresponding endif is found
                    if (_current.Evaluate(processor, ref bufferLength, ref currentBufferPosition))
                    {
                        if (_definition.WholeLine)
                        {
                            processor.SeekForwardThrough(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition);
                        }

                        return(0);
                    }

                    if (_definition.WholeLine)
                    {
                        processor.SeekForwardThrough(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition);
                    }

                    SeekToTerminator(processor, ref bufferLength, ref currentBufferPosition, out token);

                    //Keep on scanning until we've hit a balancing token that belongs to us
                    while (token == 0)
                    {
                        int open = 1;
                        while (open != 0)
                        {
                            SeekToTerminator(processor, ref bufferLength, ref currentBufferPosition, out token);
                            if (token == 0)
                            {
                                ++open;
                            }
                            else if (token == 1)
                            {
                                --open;
                            }
                        }

                        SeekToTerminator(processor, ref bufferLength, ref currentBufferPosition, out token);
                    }

                    goto BEGIN;
                }

                //If we've got an unbalanced statement, emit the token
                if (_current == null)
                {
                    byte[] tokenValue = Tokens[token];
                    target.Write(tokenValue, 0, tokenValue.Length);
                    return(tokenValue.Length);
                }

                //Got the endif token, exit to the parent "if" scope if it exists
                if (token == 1)
                {
                    _current = null;

                    if (_pendingCompletion.Count > 0)
                    {
                        _current = _pendingCompletion.Pop();
                    }

                    if (_definition._wholeLine)
                    {
                        processor.SeekForwardThrough(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition);
                    }
                    else if (_definition._trimWhitespace)
                    {
                        processor.TrimWhitespace(true, false, ref bufferLength, ref currentBufferPosition);
                    }

                    return(0);
                }

                if (_current.BranchTaken)
                {
                    processor.SeekBackUntil(processor.EncodingConfig.LineEndings, true);
                    //A previous branch was taken. Skip to the endif token.
                    SkipToMatchingEndif(processor, ref bufferLength, ref currentBufferPosition, ref token);
                    return(0);
                }

                //We have an "elseif" and haven't taken a previous branch
                if (token == _elseIfTokenIndex)
                {
                    //If the elseif branch is taken, return control for replacements to be done as usual
                    if (!_current.Evaluate(processor, ref bufferLength, ref currentBufferPosition))
                    {
                        if (_definition.WholeLine)
                        {
                            processor.SeekForwardThrough(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition);
                        }

                        if (SeekToTerminator(processor, ref bufferLength, ref currentBufferPosition, out token))
                        {
                            goto BEGIN;
                        }
                    }

                    if (_definition.WholeLine)
                    {
                        processor.SeekForwardThrough(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition);
                    }

                    //The "elseif" branch was not taken. Skip to the following else, elseif or endif token
                    return(0);
                }

                //We have an "else" token and haven't taken any other branches, return control
                //  after setting that a branch has been taken
                _current.BranchTaken = true;
                processor.WhitespaceHandler(ref bufferLength, ref currentBufferPosition, wholeLine: _definition._wholeLine, trim: _definition._trimWhitespace);
                return(0);
            }
            /// <summary>
            /// Executes specified script file as a submission.
            /// </summary>
            /// <returns>True if the code has been executed. False if the code doesn't compile.</returns>
            /// <remarks>
            /// All errors are written to the error output stream.
            /// Uses source search paths to resolve unrooted paths.
            /// </remarks>
            private async Task<ScriptState<object>> ExecuteFileAsync(EvaluationState state, string fullPath)
            {
                string content = null;
                if (fullPath != null)
                {
                    Debug.Assert(PathUtilities.IsAbsolute(fullPath));
                    try
                    {
                        content = File.ReadAllText(fullPath);
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e.Message);
                    }
                }

                ScriptState<object> newScriptState = null;
                if (content != null)
                {
                    Script<object> script = TryCompile(state.ScriptStateOpt?.Script, content, fullPath, state.ScriptOptions);
                    if (script != null)
                    {
                        newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false);
                    }
                }

                return newScriptState;
            }
Exemplo n.º 28
0
 public static CalificationsEvaluationDto Create(EmployeeEvaluation evaluation, List <string> evaluators, string currentPosition, string seniority, bool companyEvaluationDone, EvaluationState state)
 {
     return(new CalificationsEvaluationDto()
     {
         Id = evaluation.Id,
         UserName = evaluation.UserName,
         FullName = evaluation.FullName,
         CurrentPosition = currentPosition,
         Seniority = seniority,
         Project = evaluation.Project,
         ResponsibleId = evaluation.ResponsibleId,
         TemplateId = evaluation.TemplateId,
         Period = evaluation.Period,
         DevolutionInProgress = evaluation.ReadyForDevolution,
         Finished = evaluation.Finished,
         StrengthsComment = evaluation.StrengthsComment,
         ToImproveComment = evaluation.ToImproveComment,
         ActionPlanComment = evaluation.ActionPlanComment,
         Evaluators = evaluators,
         IsCompanyEvaluationDone = companyEvaluationDone,
         State = state
     });
 }
Exemplo n.º 29
0
            private EvaluationState CompleteExecution(EvaluationState state, RemoteAsyncOperation<RemoteExecutionResult> operation, bool success)
            {
                // send any updates to the host object and current directory back to the client:
                var currentSourcePaths = _globals.SourcePaths.ToArray();
                var currentReferencePaths = _globals.ReferencePaths.ToArray();
                var currentWorkingDirectory = Directory.GetCurrentDirectory();

                var changedSourcePaths = currentSourcePaths.SequenceEqual(state.SourceSearchPaths) ? null : currentSourcePaths;
                var changedReferencePaths = currentReferencePaths.SequenceEqual(state.ReferenceSearchPaths) ? null : currentReferencePaths;
                var changedWorkingDirectory = currentWorkingDirectory == state.WorkingDirectory ? null : currentWorkingDirectory;

                operation.Completed(new RemoteExecutionResult(success, changedSourcePaths, changedReferencePaths, changedWorkingDirectory));

                // no changes in resolvers:
                if (changedReferencePaths == null && changedSourcePaths == null && changedWorkingDirectory == null)
                {
                    return state;
                }

                var newSourcePaths = ImmutableArray.CreateRange(currentSourcePaths);
                var newReferencePaths = ImmutableArray.CreateRange(currentReferencePaths);
                var newWorkingDirectory = currentWorkingDirectory;

                ScriptOptions newOptions = state.ScriptOptions;
                if (changedReferencePaths != null || changedWorkingDirectory != null)
                {
                    newOptions = newOptions.WithMetadataResolver(CreateMetadataReferenceResolver(newReferencePaths, newWorkingDirectory));
                }

                if (changedSourcePaths != null || changedWorkingDirectory != null)
                {
                    newOptions = newOptions.WithSourceResolver(CreateSourceReferenceResolver(newSourcePaths, newWorkingDirectory));
                }

                return new EvaluationState(
                    state.ScriptStateOpt,
                    newOptions,
                    newSourcePaths,
                    newReferencePaths,
                    workingDirectory: newWorkingDirectory);
            }
Exemplo n.º 30
0
 public override void Evaluate <T>(
     ICircuitEvaluator <T> evaluator,
     EvaluationState <T> evaluationState)
 {
     evaluationState.SetOutput(_outputIndex, evaluationState.GetGateEvaluationValue(_inputGate));
 }
Exemplo n.º 31
0
            /// <summary>
            /// Executes specified script file as a submission.
            /// </summary>
            /// <remarks>
            /// All errors are written to the error output stream.
            /// Uses source search paths to resolve unrooted paths.
            /// </remarks>
            private async Task<ScriptState<object>> TryExecuteFileAsync(EvaluationState state, string fullPath)
            {
                Debug.Assert(PathUtilities.IsAbsolute(fullPath));

                string content = null;
                try
                {
                    using (var reader = File.OpenText(fullPath))
                    {
                        content = await reader.ReadToEndAsync().ConfigureAwait(false);
                    }
                }
                catch (Exception e)
                {
                    // file read errors:
                    Console.Error.WriteLine(e.Message);
                    return null;
                }

                Script<object> script = TryCompile(state.ScriptStateOpt?.Script, content, fullPath, state.ScriptOptions);
                if (script == null)
                {
                    // compilation errors:
                    return null;
                }

                return await ExecuteOnUIThread(script, state.ScriptStateOpt, displayResult: false).ConfigureAwait(false);
            }
 private EvaluationResult(EvaluationState state, [CanBeNull] string deferredOperationNameOrNull)
 {
     evaluationState = state;
     this.deferredOperationNameOrNull = deferredOperationNameOrNull;
 }
Exemplo n.º 33
0
 public void Reset()
 {
     scopeStack.Clear();
     PushScope(new Scope());
     ResetTimer();
     evaluationState = EvaluationState.Normal;
     callDepth = 0;
 }
 public void SetImmediate()
 {
     evaluationState = EvaluationState.Immediate;
 }
Exemplo n.º 35
0
		public EvaluationResult Evaluate(EvaluationState state, ReadOnlyList<IEvaluate> args, ReadOnlyList<Object> data)
		{
			return BaseOperations.LogicalOr(args[0].Evaluate(state), args[1].Evaluate(state));
		}
 public void SetUnknown()
 {
     evaluationState = EvaluationState.Unknown;
 }