コード例 #1
0
        private async Task <FindReferencesResult> GetReferences(ScriptRegion scriptRegion)
        {
            ScriptFile scriptFile = GetScriptFile(scriptRegion);

            SymbolReference symbolReference =
                this.languageService.FindSymbolAtLocation(
                    scriptFile,
                    scriptRegion.StartLineNumber,
                    scriptRegion.StartColumnNumber);

            Assert.NotNull(symbolReference);

            return
                (await this.languageService.FindReferencesOfSymbol(
                     symbolReference,
                     this.workspace.ExpandScriptReferences(scriptFile)));
        }
コード例 #2
0
        /// <summary>
        /// Finds all the occurences of a symbol in the script given a file location
        /// </summary>
        /// <param name="file">The details and contents of a open script file</param>
        /// <param name="symbolLineNumber">The line number of the cursor for the given script</param>
        /// <param name="symbolColumnNumber">The coulumn number of the cursor for the given script</param>
        /// <returns>FindOccurrencesResult</returns>
        public static IReadOnlyList <SymbolReference> FindOccurrencesInFile(
            ScriptFile file,
            int symbolLineNumber,
            int symbolColumnNumber)
        {
            SymbolReference foundSymbol = AstOperations.FindSymbolAtPosition(
                file.ScriptAst,
                symbolLineNumber,
                symbolColumnNumber);

            if (foundSymbol == null)
            {
                return(null);
            }

            return(AstOperations.FindReferencesOfSymbol(file.ScriptAst, foundSymbol).ToArray());
        }
コード例 #3
0
ファイル: Expressions.cs プロジェクト: henbagle/ME3Explorer
        public Expression DecompileNativeFunction(ushort index)
        {
            var parameters = new List <Expression>();

            while (!CurrentIs(OpCodes.EndFunctionParms))
            {
                var param = DecompileExpression();
                if (param == null)
                {
                    return(null); // ERROR
                }
                parameters.Add(param);
            }
            PopByte();

            var        entry = NativeTable[index];
            Expression call  = null;

            switch (entry.Type)
            {
            case NativeType.Function:
                var func = new SymbolReference(null, entry.Name);
                call = new FunctionCall(func, parameters, null, null);
                break;

            case NativeType.Operator:
                var op    = new InOpDeclaration(entry.Name, entry.Precedence, index, null, null, null);
                var opRef = new InOpReference(op, parameters[0], parameters[1]);
                DecompileEnumOperatorComparisons(opRef);
                call = opRef;
                break;

            case NativeType.PreOperator:
                var preOp = new PreOpDeclaration(entry.Name, null, index, null);
                call = new PreOpReference(preOp, parameters[0]);
                break;

            case NativeType.PostOperator:
                var postOp = new PostOpDeclaration(entry.Name, null, index, null);
                call = new PostOpReference(postOp, parameters[0], null, null);
                break;
            }

            StartPositions.Pop();
            return(call);
        }
コード例 #4
0
        /// <summary>
        /// Reads symbol record from symbol references for the specified index.
        /// </summary>
        /// <param name="index">Index of the symbol record.</param>
        private SymbolRecord GetSymbol(int index)
        {
            // Since DictionaryCache is allowing only single thread to call this function, we don't need to lock reader here.
            SymbolReference reference = references[index];

            Reader.Position = reference.DataOffset;
            switch (reference.Kind)
            {
            case SymbolRecordKind.S_GPROC32:
            case SymbolRecordKind.S_LPROC32:
            case SymbolRecordKind.S_GPROC32_ID:
            case SymbolRecordKind.S_LPROC32_ID:
            case SymbolRecordKind.S_LPROC32_DPC:
            case SymbolRecordKind.S_LPROC32_DPC_ID:
                return(ProcedureSymbol.Read(Reader, reference.Kind));

            case SymbolRecordKind.S_PUB32:
                return(Public32Symbol.Read(Reader, reference.Kind));

            case SymbolRecordKind.S_CONSTANT:
            case SymbolRecordKind.S_MANCONSTANT:
                return(ConstantSymbol.Read(Reader, reference.Kind));

            case SymbolRecordKind.S_LDATA32:
            case SymbolRecordKind.S_GDATA32:
            case SymbolRecordKind.S_LMANDATA:
            case SymbolRecordKind.S_GMANDATA:
                return(DataSymbol.Read(Reader, reference.Kind));

            case SymbolRecordKind.S_PROCREF:
            case SymbolRecordKind.S_LPROCREF:
                return(ProcedureReferenceSymbol.Read(Reader, reference.Kind));

            case SymbolRecordKind.S_UDT:
            case SymbolRecordKind.S_COBOLUDT:
                return(UdtSymbol.Read(Reader, reference.Kind));

            case SymbolRecordKind.S_LTHREAD32:
            case SymbolRecordKind.S_GTHREAD32:
                return(ThreadLocalDataSymbol.Read(Reader, reference.Kind));

            default:
                throw new NotImplementedException();
            }
        }
コード例 #5
0
    public override TypeDefinitionBase SubstituteTypeParameters(SymbolDefinition context)
    {
        var target     = this;
        var parentType = parentSymbol as TypeDefinitionBase;

        if (parentType != null)
        {
            parentType = parentType.SubstituteTypeParameters(context);
            var constructedParent = parentType as SD_Type_Constructed;
            if (constructedParent != null)
            {
                target = constructedParent.GetConstructedMember(this.genericTypeDefinition) as SD_Type_Constructed;
            }
        }

        if (typeArguments == null)
        {
            return(target);
        }

        var constructNew = false;
        var newArguments = new SymbolReference[typeArguments.Length];

        for (var i = 0; i < newArguments.Length; ++i)
        {
            newArguments[i] = typeArguments[i];
            var original = typeArguments[i] != null ? typeArguments[i].Definition as TypeDefinitionBase : null;
            if (original == null)
            {
                continue;
            }
            var substitute = original.SubstituteTypeParameters(target);
            substitute = substitute.SubstituteTypeParameters(context);
            if (substitute != original)
            {
                newArguments[i] = new SymbolReference(substitute);
                constructNew    = true;
            }
        }
        if (!constructNew)
        {
            return(target);
        }
        return(ConstructType(newArguments));
    }
コード例 #6
0
 /// <summary>
 /// Checks if the current symbol reference is contained in the aready collected Items list.
 /// </summary>
 /// <param name="sr">The Symbol Reference to Check</param>
 /// <returns>True if it is aready in, false otherwise</returns>
 private bool Containss(SymbolReference sr)
 {
     if (AllItemsList == null)
     {
         return(false);
     }
     foreach (var l in AllItemsList)
     {
         foreach (SymbolReference r in l)
         {
             if (sr == r)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
コード例 #7
0
        private List <SymbolReference> GetReferences(ScriptRegion scriptRegion)
        {
            ScriptFile scriptFile = GetScriptFile(scriptRegion);

            SymbolReference symbolReference =
                SymbolsService.FindSymbolAtLocation(
                    scriptFile,
                    scriptRegion.StartLineNumber,
                    scriptRegion.StartColumnNumber);

            Assert.NotNull(symbolReference);

            return
                (this.symbolsService.FindReferencesOfSymbol(
                     symbolReference,
                     this.workspace.ExpandScriptReferences(scriptFile),
                     this.workspace));
        }
コード例 #8
0
        /// <summary>
        /// Finds the symbol in the script given a file location
        /// </summary>
        /// <param name="scriptFile">The details and contents of a open script file</param>
        /// <param name="lineNumber">The line number of the cursor for the given script</param>
        /// <param name="columnNumber">The coulumn number of the cursor for the given script</param>
        /// <returns>A SymbolReference of the symbol found at the given location
        /// or null if there is no symbol at that location
        /// </returns>
        public SymbolReference FindSymbolAtLocation(
            ScriptFile scriptFile,
            int lineNumber,
            int columnNumber)
        {
            SymbolReference symbolReference =
                AstOperations.FindSymbolAtPosition(
                    scriptFile.ScriptAst,
                    lineNumber,
                    columnNumber);

            if (symbolReference != null)
            {
                symbolReference.FilePath = scriptFile.FilePath;
            }

            return(symbolReference);
        }
コード例 #9
0
ファイル: Expressions.cs プロジェクト: henbagle/ME3Explorer
        static bool ResolveEnumValues(ref Expression a, ref Expression b)
        {
            SymbolReference symRef = a as SymbolReference;

            if (symRef is null && a is CastExpression cast && cast.CastType.Name == INT)
            {
                symRef = cast.CastTarget as SymbolReference;
            }

            if (symRef?.Node is Enumeration enm && b is IntegerLiteral intLit && intLit.Value >= 0 && intLit.Value < enm.Values.Count)
            {
                a = symRef;
                b = new SymbolReference(enm.Values[intLit.Value], enm.Values[intLit.Value].Name);
                return(true);
            }

            return(false);
        }
コード例 #10
0
        private async Task <GetDefinitionResult> GetDefinition(ScriptRegion scriptRegion, Workspace workspace)
        {
            ScriptFile scriptFile = GetScriptFile(scriptRegion);

            SymbolReference symbolReference =
                this.languageService.FindSymbolAtLocation(
                    scriptFile,
                    scriptRegion.StartLineNumber,
                    scriptRegion.StartColumnNumber);

            Assert.NotNull(symbolReference);

            return
                (await this.languageService.GetDefinitionOfSymbol(
                     scriptFile,
                     symbolReference,
                     workspace));
        }
コード例 #11
0
        public void AddSymbolReference(Identifier identifier, AstNode ownerNode)
        {
            this.EnsureCurrentScopeDefined();

            var newRef = new SymbolReference()
            {
                Name           = identifier.Name,
                IdentifierNode = identifier,
                OwnerNode      = ownerNode
            };

            if (!this.CurrentScope.References.ContainsKey(identifier.Name))
            {
                this.CurrentScope.References.Add(identifier.Name, new List <SymbolReference>());
            }

            this.CurrentScope.References[identifier.Name].Add(newRef);
        }
コード例 #12
0
ファイル: Expressions.cs プロジェクト: Mgamerz/ME3Libs
        public Expression DecompileNativeFunction(UInt16 index)
        {
            var parameters = new List <Expression>();

            while (!CurrentIs(StandardByteCodes.EndFunctionParms))
            {
                var param = DecompileExpression();
                if (param == null)
                {
                    return(null); // ERROR
                }
                parameters.Add(param);
            }
            PopByte();

            var        entry = NativeTable[index];
            Expression call  = null;

            switch (entry.Type)
            {
            case NativeType.Function:
                var func = new SymbolReference(null, null, null, entry.Name);
                call = new FunctionCall(func, parameters, null, null);
                break;

            case NativeType.Operator:       // TODO: table should hold precedence, currently all have 0 and it'll be a mess.
                var op = new InOpDeclaration(entry.Name, entry.Precedence, false, null, null, null, null, null, null, null);
                call = new InOpReference(op, parameters[0], parameters[1], null, null);
                break;

            case NativeType.PreOperator:       // TODO: table should hold precedence, currently all have 0 and it'll be a mess.
                var preOp = new PreOpDeclaration(entry.Name, false, null, null, null, null, null, null);
                call = new PreOpReference(preOp, parameters[0], null, null);
                break;

            case NativeType.PostOperator:       // TODO: table should hold precedence, currently all have 0 and it'll be a mess.
                var postOp = new PostOpDeclaration(entry.Name, false, null, null, null, null, null, null);
                call = new PostOpReference(postOp, parameters[0], null, null);
                break;
            }

            StartPositions.Pop();
            return(call);
        }
コード例 #13
0
        protected async Task HandleReferencesRequest(
            ReferencesParams referencesParams,
            EditorSession editorSession,
            RequestContext <Location[], object> requestContext)
        {
            ScriptFile scriptFile =
                editorSession.Workspace.GetFile(
                    referencesParams.Uri);

            SymbolReference foundSymbol =
                editorSession.LanguageService.FindSymbolAtLocation(
                    scriptFile,
                    referencesParams.Position.Line + 1,
                    referencesParams.Position.Character + 1);

            FindReferencesResult referencesResult =
                await editorSession.LanguageService.FindReferencesOfSymbol(
                    foundSymbol,
                    editorSession.Workspace.ExpandScriptReferences(scriptFile));

            Location[] referenceLocations = null;

            if (referencesResult != null)
            {
                referenceLocations =
                    referencesResult
                    .FoundReferences
                    .Select(r =>
                {
                    return(new Location
                    {
                        Uri = new Uri(r.FilePath).AbsoluteUri,
                        Range = GetRangeFromScriptRegion(r.ScriptRegion)
                    });
                })
                    .ToArray();
            }
            else
            {
                referenceLocations = new Location[0];
            }

            await requestContext.SendResult(referenceLocations);
        }
コード例 #14
0
ファイル: CodeBodyParser.cs プロジェクト: Mgamerz/ME3Libs
        public SymbolReference TryParseBasicRef(Expression compositeOuter = null)
        {
            Func <ASTNode> refParser = () =>
            {
                var token = Tokens.ConsumeToken(TokenType.Word);
                if (token == null)
                {
                    return(null);
                }

                ASTNode         symbol = null;
                FunctionCall    func   = compositeOuter as FunctionCall;
                SymbolReference outer  = compositeOuter as SymbolReference;

                if (func != null)
                {
                    var containingClass = NodeUtils.GetContainingClass(func.ResolveType().Declaration);
                    if (!Symbols.TryGetSymbolFromSpecificScope(token.Value, out symbol, containingClass.GetInheritanceString() + "." + func.Function.Name))
                    {
                        return(Error("Left side has no member named '" + func.Function.Name + "'!", token.StartPosition, token.EndPosition));
                    }
                }
                else if (outer != null)
                {
                    var containingClass = NodeUtils.GetContainingClass(outer.ResolveType().Declaration);
                    if (!Symbols.TryGetSymbolFromSpecificScope(token.Value, out symbol, containingClass.GetInheritanceString() + "." + outer.ResolveType().Name))
                    {
                        return(Error("Left side has no member named '" + outer.Name + "'!", token.StartPosition, token.EndPosition));
                    }
                }
                else
                {
                    if (!Symbols.TryGetSymbol(token.Value, out symbol, NodeUtils.GetOuterClassScope(Node)))
                    {
                        return(Error("No symbol named '" + token.Value + "' exists in the current scope!", token.StartPosition, token.EndPosition));
                    }
                }

                return(new SymbolReference(symbol, token.StartPosition, token.EndPosition, token.Value));
            };

            return((SymbolReference)Tokens.TryGetTree(refParser));
        }
コード例 #15
0
        private void ResolveSymbolReference(SymbolReference reference, Scope containingScope)
        {
            if (reference.OwnerNode is ExpressionFieldSelection)
            {
                //// Not implemented at the moment, requires to solve left side type.
                return;
            }

            if (reference.OwnerNode is ExpressionFunctionCall)
            {
                ExpressionFunctionCall call = reference.OwnerNode as ExpressionFunctionCall;
                if (call.Left != null)
                {
                    //// Not implemented at the moment, requires to solve left side type.
                    return;
                }

                reference.ResolvedSymbol = this.LookupSymbol(reference.Name, SymbolKind.Function | SymbolKind.Type, containingScope, reference.OwnerNode);
                return;
            }

            if (reference.OwnerNode is ExpressionVariableIdentifier)
            {
                reference.ResolvedSymbol = this.LookupSymbol(reference.Name, SymbolKind.Variable | SymbolKind.FunctionParameter, containingScope, reference.OwnerNode);
                return;
            }

            if (reference.OwnerNode is LayoutIdQualifier)
            {
                //// Not implemented at the moment, requires to solve which type this qualifier is for.
                return;
            }

            if (reference.OwnerNode is TypeNameSpecifier)
            {
                reference.ResolvedSymbol = this.LookupSymbol(reference.Name, SymbolKind.Type, containingScope, reference.OwnerNode);
                return;
            }

            throw new NotImplementedException($"Cannot resolve symbol reference for {reference.OwnerNode.GetType()}.");
        }
コード例 #16
0
ファイル: Expressions.cs プロジェクト: Mgamerz/ME3Libs
        public Expression DecompileStructMember()
        {
            PopByte();

            var MemberRef = ReadObject();
            var StructRef = ReadObject();

            ReadByte(); // discard unknown bytes
            ReadByte();

            var expr = DecompileExpression(); // get the expression for struct instance

            if (expr == null)
            {
                return(null); // ERROR
            }
            StartPositions.Pop();
            var member = new SymbolReference(null, null, null, MemberRef.ObjectName);

            return(new CompositeSymbolRef(expr, member, null, null));
        }
コード例 #17
0
    public override List <SymbolReference> Interfaces()
    {
        if (arrayGenericInterfaces == null && rank == 1)
        {
            arrayGenericInterfaces = new List <SymbolReference> {
                ReflectedTypeReference.ForType(typeof(IEnumerable <>)),
                ReflectedTypeReference.ForType(typeof(IList <>)),
                ReflectedTypeReference.ForType(typeof(ICollection <>)),
            };

            var typeArguments = new[] { new SymbolReference(elementType) };
            for (var i = 0; i < arrayGenericInterfaces.Count; ++i)
            {
                var genericInterface = arrayGenericInterfaces[i].Definition as SD_Type;
                genericInterface          = genericInterface.ConstructType(typeArguments);
                arrayGenericInterfaces[i] = new SymbolReference(genericInterface);
            }
        }
        interfaces = arrayGenericInterfaces ?? base.Interfaces();
        return(interfaces);
    }
コード例 #18
0
ファイル: ExpressionCompiler.cs プロジェクト: MasterQ32/psi
        LLVMValueRef IExpressionVisitor.Visit(SymbolReference exp)
        {
            var target = exp.Symbol;

            switch (target.Kind)
            {
            case SymbolKind.Builtin:
            case SymbolKind.Extern:
            case SymbolKind.Global:
                return(codegen.GetGlobalVariable(exp.Symbol));

            case SymbolKind.Local:
                throw new NotImplementedException();

            case SymbolKind.Parameter:
                return(LLVM.GetParam(function, (uint)exp.Symbol.ParameterIndex));

            default:
                throw new NotImplementedException();
            }
        }
コード例 #19
0
        private string CreateName(SymbolReference symbolReference)
        {
            var name  = symbolReference.Name;
            var found = table.GetVariable(symbolReference);

            if (found.Count < 1)
            {
                return("?NOT_FOUND?");
            }
            if (found.Count > 1)
            {
                return(name);
            }
            var pentry = (DataDescriptionEntry)found[0].CodeElement;

            if (pentry.DataType == DataType.Boolean)
            {
                return(name + "-value");
            }
            return(name);
        }
コード例 #20
0
        protected async Task HandleDefinitionRequest(
            TextDocumentPosition textDocumentPosition,
            EditorSession editorSession,
            RequestContext <Location[], object> requestContext)
        {
            ScriptFile scriptFile =
                editorSession.Workspace.GetFile(
                    textDocumentPosition.Uri);

            SymbolReference foundSymbol =
                editorSession.LanguageService.FindSymbolAtLocation(
                    scriptFile,
                    textDocumentPosition.Position.Line + 1,
                    textDocumentPosition.Position.Character + 1);

            List <Location> definitionLocations = new List <Location>();

            GetDefinitionResult definition = null;

            if (foundSymbol != null)
            {
                definition =
                    await editorSession.LanguageService.GetDefinitionOfSymbol(
                        scriptFile,
                        foundSymbol,
                        editorSession.Workspace);

                if (definition != null)
                {
                    definitionLocations.Add(
                        new Location
                    {
                        Uri   = new Uri(definition.FoundDefinition.FilePath).AbsoluteUri,
                        Range = GetRangeFromScriptRegion(definition.FoundDefinition.ScriptRegion)
                    });
                }
            }

            await requestContext.SendResult(definitionLocations.ToArray());
        }
コード例 #21
0
        /// <summary>
        /// Finds the details of the symbol at the given script file location.
        /// </summary>
        /// <param name="scriptFile">The ScriptFile in which the symbol can be located.</param>
        /// <param name="lineNumber">The line number at which the symbol can be located.</param>
        /// <param name="columnNumber">The column number at which the symbol can be located.</param>
        /// <returns></returns>
        public Task <SymbolDetails> FindSymbolDetailsAtLocationAsync(
            ScriptFile scriptFile,
            int lineNumber,
            int columnNumber)
        {
            SymbolReference symbolReference =
                AstOperations.FindSymbolAtPosition(
                    scriptFile.ScriptAst,
                    lineNumber,
                    columnNumber);

            if (symbolReference == null)
            {
                return(Task.FromResult <SymbolDetails>(null));
            }

            symbolReference.FilePath = scriptFile.FilePath;
            return(SymbolDetails.CreateAsync(
                       symbolReference,
                       _runspaceContext.CurrentRunspace,
                       _executionService));
        }
コード例 #22
0
        private static void CheckNotInTable(SymbolTable table, SymbolReference symbol, Node node)
        {
            if (symbol == null)
            {
                return;
            }
            string message = "TCRFUN_NO_PERFORM_OF_ENCLOSING_PROGRAM";
            var    found   = table.GetSection(symbol.Name);

            if (found.Count > 0)
            {
                DiagnosticUtils.AddError(node, message, symbol);
            }
            else
            {
                var paragraphFounds = table.GetParagraph(symbol.Name);
                if (paragraphFounds.Count > 0)
                {
                    DiagnosticUtils.AddError(node, message, symbol);
                }
            }
        }
コード例 #23
0
        private void Check(SymbolReference renames, Node node)
        {
            var found = node.SymbolTable.GetVariable(renames);

            if (found.Count > 1)
            {
                string message = "Illegal RENAMES: Ambiguous reference to symbol \'" + renames + "\'";
                DiagnosticUtils.AddError(node.CodeElement, message, MessageCode.SemanticTCErrorInParser);
            }
            if (found.Count < 1)
            {
                string message = "Illegal RENAMES: Symbol \'" + renames + "\' is not referenced";
                DiagnosticUtils.AddError(node.CodeElement, message, MessageCode.SemanticTCErrorInParser);
            }
            foreach (var v in found)
            {
                if (v.IsStronglyTyped || v.IsStrictlyTyped)
                {
                    string message = string.Format("Illegal RENAMES: '{0}' is {1}", renames, v.IsStronglyTyped ? "strongly-typed" : "strictly-typed");
                    DiagnosticUtils.AddError(node.CodeElement, message, MessageCode.SemanticTCErrorInParser);
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// Finds the details of the symbol at the given script file location.
        /// </summary>
        /// <param name="scriptFile">The ScriptFile in which the symbol can be located.</param>
        /// <param name="lineNumber">The line number at which the symbol can be located.</param>
        /// <param name="columnNumber">The column number at which the symbol can be located.</param>
        /// <returns></returns>
        public async Task <SymbolDetails> FindSymbolDetailsAtLocationAsync(
            ScriptFile scriptFile,
            int lineNumber,
            int columnNumber)
        {
            SymbolReference symbolReference =
                AstOperations.FindSymbolAtPosition(
                    scriptFile.ScriptAst,
                    lineNumber,
                    columnNumber);

            if (symbolReference == null)
            {
                return(null);
            }

            symbolReference.FilePath = scriptFile.FilePath;
            SymbolDetails symbolDetails = await SymbolDetails.CreateAsync(
                symbolReference,
                _powerShellContextService).ConfigureAwait(false);

            return(symbolDetails);
        }
コード例 #25
0
ファイル: SymbolTable.cs プロジェクト: jdrew1303/TypeCobol
        public DataDefinition GetRedefinedVariable(DataRedefines redefinesNode, SymbolReference symbolReference)
        {
            var childrens = redefinesNode.Parent.Children;
            int index     = redefinesNode.Parent.IndexOf(redefinesNode);

            bool redefinedVariableFound = false;

            while (!redefinedVariableFound && index >= 0)
            {
                CommonDataDescriptionAndDataRedefines child = childrens[index].CodeElement as DataDescriptionEntry ??
                                                              (CommonDataDescriptionAndDataRedefines)
                                                              (childrens[index].CodeElement as DataRedefinesEntry);

                if (child != null && (child is DataDescriptionEntry || child is DataRedefinesEntry))
                {
                    if (child.DataName != null &&
                        string.Equals(child.DataName.Name, symbolReference.Name,
                                      StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(childrens[index] as DataDefinition);
                    }
                    else if (child.DataName != null && child is DataDescriptionEntry &&
                             !string.Equals(child.DataName.Name, symbolReference.Name,
                                            StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }

                index--;
            }
            return(null);
        }
コード例 #26
0
        ////////////////////
        // PROCEDURE CALL //
        ////////////////////

        public override void EnterTcCallStatement(CodeElementsParser.TcCallStatementContext context)
        {
            var cbCallProc = context.procedurePointerOrFunctionPointerVariableOrfunctionNameReference;

            // Register call parameters (shared storage areas) information at the CodeElement level
            CallSite callSite = null;
            ProcedureStyleCallStatement statement = null;

            Context = context;

            //Incomplete CallStatement, create an empty CodeElement and return + Error due to issue #774
            if (cbCallProc == null)
            {
                CodeElement = new ProcedureStyleCallStatement
                {
                    Diagnostics = new List <Diagnostic>
                    {
                        new Diagnostic(MessageCode.SyntaxErrorInParser, context.Start.Column,
                                       context.Stop.Column, context.Start.Line, "Empty CALL is not authorized")
                    }
                };
                return;
            }


            //Here ambiguousSymbolReference with either CandidatesType:
            // - ProgramNameOrProgramEntry
            // - data, condition, UPSISwitch, TCFunctionName
            var ambiguousSymbolReference = CobolExpressionsBuilder.CreateProcedurePointerOrFunctionPointerVariableOrTCFunctionProcedure(cbCallProc);


            //If (inputs, inouts ou outputs).Count > 0, then it's a procedure call
            if (context.callOutputParameter().Length > 0 || context.callInputParameter().Length > 0 || context.callInoutParameter().Length > 0)
            {
                callSite = new CallSite();
                #region Setup Input Output Inout CallSitesParameters

                var inputs  = new List <CallSiteParameter>();
                var inouts  = new List <CallSiteParameter>();
                var outputs = new List <CallSiteParameter>();

                SyntaxProperty <ParameterSharingMode> mode = null;
                foreach (var p in context.callInputParameter())
                {
                    CreateSharingMode(p, ref mode); // TCRFUN_INPUT_BY
                    var callSiteParameter = new CallSiteParameter
                    {
                        SharingMode = mode,
                    };


                    if (p.sharedVariableOrFileName() != null)
                    {
                        callSiteParameter.StorageAreaOrValue = CobolExpressionsBuilder.CreateSharedVariableOrFileName(p.sharedVariableOrFileName());
                    }
                    else if (p.OMITTED() != null)
                    {
                        callSiteParameter.Omitted = new SyntaxProperty <bool>(true, ParseTreeUtils.GetFirstToken(p.OMITTED()));
                    }

                    if (p.sharedVariableOrFileName() != null || p.OMITTED() != null)
                    {
                        inputs.Add(callSiteParameter);
                    }
                }

                foreach (var p in context.callInoutParameter())
                {
                    var callSiteParameter = new CallSiteParameter
                    {
                        // TCRFUN_CALL_INOUT_AND_OUTPUT_BY_REFERENCE
                        SharingMode =
                            new SyntaxProperty <ParameterSharingMode>(ParameterSharingMode.ByReference, null),
                    };

                    if (p.sharedStorageArea1() != null)
                    {
                        callSiteParameter.StorageAreaOrValue = new Variable(CobolExpressionsBuilder.CreateSharedStorageArea(p.sharedStorageArea1()));
                    }
                    else if (p.OMITTED() != null)
                    {
                        callSiteParameter.Omitted = new SyntaxProperty <bool>(true, ParseTreeUtils.GetFirstToken(p.OMITTED()));
                    }

                    if (p.sharedStorageArea1() != null || p.OMITTED() != null)
                    {
                        inouts.Add(callSiteParameter);
                    }
                }

                foreach (var p in context.callOutputParameter())
                {
                    var callSiteParameter = new CallSiteParameter
                    {
                        // TCRFUN_CALL_INOUT_AND_OUTPUT_BY_REFERENCE
                        SharingMode =
                            new SyntaxProperty <ParameterSharingMode>(ParameterSharingMode.ByReference, null),
                    };

                    if (p.sharedStorageArea1() != null)
                    {
                        callSiteParameter.StorageAreaOrValue = new Variable(CobolExpressionsBuilder.CreateSharedStorageArea(p.sharedStorageArea1()));
                    }
                    else if (p.OMITTED() != null)
                    {
                        callSiteParameter.Omitted = new SyntaxProperty <bool>(true, ParseTreeUtils.GetFirstToken(p.OMITTED()));
                    }

                    if (p.sharedStorageArea1() != null || p.OMITTED() != null)
                    {
                        outputs.Add(callSiteParameter);
                    }
                }

                int parametersCount = inputs.Count + outputs.Count + inouts.Count;
                callSite.Parameters = new CallSiteParameter[parametersCount];
                int i = 0;

                //Add inputs to global callsites parameters
                if (inputs.Count > 0)
                {
                    foreach (var param in inputs)
                    {
                        callSite.Parameters[i] = param;
                        i++;
                    }
                }

                //Add outputs to global callsites parameters
                if (outputs.Count > 0)
                {
                    foreach (var param in outputs)
                    {
                        callSite.Parameters[i] = param;
                        i++;
                    }
                }

                //Add inouts to global callsites parameters
                if (inouts.Count > 0)
                {
                    foreach (var param in inouts)
                    {
                        callSite.Parameters[i] = param;
                        i++;
                    }
                }

                #endregion

                //Check Type or CandidatesTypes to see if a TCFunctionName is possible
                if (ambiguousSymbolReference.MainSymbolReference != null &&
                    ambiguousSymbolReference.MainSymbolReference.IsOrCanBeOfType(SymbolType.TCFunctionName))
                {
                    SymbolReferenceVariable TCFunctionNameRefVariable;

                    if (ambiguousSymbolReference.MainSymbolReference.IsQualifiedReference)
                    {
                        var nonAmbiguousHead =
                            new SymbolReference(
                                (ambiguousSymbolReference.MainSymbolReference as TypeCobolQualifiedSymbolReference)?.Head
                                .NameLiteral, SymbolType.TCFunctionName);
                        var nonAmbiguousTail =
                            new SymbolReference(
                                (ambiguousSymbolReference.MainSymbolReference as TypeCobolQualifiedSymbolReference)?.Tail
                                .NameLiteral, SymbolType.ProgramName);

                        TypeCobolQualifiedSymbolReference newQualifiedSymbolReferece =
                            new TypeCobolQualifiedSymbolReference(nonAmbiguousHead, nonAmbiguousTail);
                        TCFunctionNameRefVariable = new SymbolReferenceVariable(StorageDataType.MethodName,
                                                                                newQualifiedSymbolReferece);
                    }
                    else
                    {
                        //If so, create ProcedureStyleCallStatement with a ProcedureCall and fix SymbolReference so it's not ambiguous
                        var nonAmbiguousSymbolRef =
                            new SymbolReference(ambiguousSymbolReference.MainSymbolReference.NameLiteral,
                                                SymbolType.TCFunctionName);
                        TCFunctionNameRefVariable = new SymbolReferenceVariable(StorageDataType.MethodName,
                                                                                nonAmbiguousSymbolRef);
                    }

                    //CobolExpressionsBuilder store every StorageArea created into storageAreaReads and then after
                    //storageAreaReads is set to the CodeElement
                    //We must remove it as TCFunctionNameRefVariable doesn't contains a StorageArea
                    if (ambiguousSymbolReference.StorageArea != null)
                    {
                        CobolExpressionsBuilder.storageAreaReads.Remove(ambiguousSymbolReference.StorageArea);
                    }

                    statement =
                        new ProcedureStyleCallStatement(new ProcedureCall(TCFunctionNameRefVariable.MainSymbolReference,
                                                                          inputs, inouts, outputs))
                    {
                        ProgramOrProgramEntryOrProcedureOrFunctionOrTCProcedureFunction =
                            TCFunctionNameRefVariable.MainSymbolReference
                    };

                    callSite.CallTarget = TCFunctionNameRefVariable.MainSymbolReference;
                }
                else
                {
                    //else it's an error
                    statement =
                        new ProcedureStyleCallStatement(new ProcedureCall(ambiguousSymbolReference.MainSymbolReference,
                                                                          inputs, inouts, outputs))
                    {
                        ProgramOrProgramEntryOrProcedureOrFunctionOrTCProcedureFunction = ambiguousSymbolReference.MainSymbolReference,
                        Diagnostics = new List <Diagnostic>
                        {
                            new Diagnostic(MessageCode.ImplementationError, context.Start.Column,
                                           context.Stop.Column, context.Start.Line,
                                           "A call with arguments is not a TCFunctionName")
                        },
                    };

                    callSite.CallTarget = ambiguousSymbolReference.MainSymbolReference;
                }
            }
            else
            {
                if (ambiguousSymbolReference.MainSymbolReference != null &&
                    ambiguousSymbolReference.MainSymbolReference.IsOrCanBeOfType(SymbolType.DataName, SymbolType.TCFunctionName))
                {
                    //TODO think about uniformity of CandidateTypes inside QualifiedReference.
                    //Maybe just define CandidatesTypes for the Head...
                    if (ambiguousSymbolReference.MainSymbolReference.IsQualifiedReference)
                    {
                        var qualifiedSymbolReference = (QualifiedSymbolReference)ambiguousSymbolReference.MainSymbolReference;


                        AmbiguousSymbolReference.ApplyCandidatesTypes(qualifiedSymbolReference, new[] { SymbolType.DataName, SymbolType.ProgramName });
                        //Adjust candidate types only for the first element
                        if (qualifiedSymbolReference.First.IsAmbiguous)
                        {
                            ((AmbiguousSymbolReference)qualifiedSymbolReference.First).CandidateTypes = new[] { SymbolType.DataName, SymbolType.TCFunctionName };
                        }
                    }
                    else
                    {
                        ((AmbiguousSymbolReference)ambiguousSymbolReference.MainSymbolReference).CandidateTypes = new[] { SymbolType.DataName, SymbolType.TCFunctionName };
                    }

                    statement = new ProcedureStyleCallStatement(new ProcedureCall(ambiguousSymbolReference.MainSymbolReference,
                                                                                  null, null, null))
                    {
                        ProcdurePointerOrTCProcedureFunction = ambiguousSymbolReference.MainSymbolReference
                    };
                    callSite            = new CallSite();
                    callSite.CallTarget = statement.ProcdurePointerOrTCProcedureFunction;
                }
                else     //else, it's an error
                {
                    statement =
                        new ProcedureStyleCallStatement(new ProcedureCall(ambiguousSymbolReference.MainSymbolReference,
                                                                          null, null, null))
                    {
                        ProgramOrProgramEntryOrProcedureOrFunctionOrTCProcedureFunction =
                            ambiguousSymbolReference.MainSymbolReference,
                    };
                    statement.Diagnostics.Add(new Diagnostic(MessageCode.SyntaxErrorInParser, context.Start.Column,
                                                             context.Stop.Column, context.Start.Line, "Error in detecting Procedure Call type"));
                    callSite            = new CallSite();
                    callSite.CallTarget = statement.ProgramOrProgramEntryOrProcedureOrFunctionOrTCProcedureFunction;
                }
            }


            if (callSite != null)
            {
                if (statement.CallSites == null)
                {
                    statement.CallSites = new List <CallSite>();
                }
                statement.CallSites.Add(callSite);
            }

            CodeElement = statement;
        }
コード例 #27
0
 private static bool NotNull(SymbolReference reference)
 {
     return(reference.SymbolResult.Symbol != null);
 }
コード例 #28
0
        private static bool NotGlobalNamespace(SymbolReference reference)
        {
            var symbol = reference.SymbolResult.Symbol;

            return(symbol.IsNamespace ? !((INamespaceSymbol)symbol).IsGlobalNamespace : true);
        }
コード例 #29
0
        /// <summary>
        /// Finds all the references of a symbol
        /// </summary>
        /// <param name="foundSymbol">The symbol to find all references for</param>
        /// <param name="referencedFiles">An array of scriptFiles too search for references in</param>
        /// <param name="workspace">The workspace that will be searched for symbols</param>
        /// <returns>FindReferencesResult</returns>
        public List <SymbolReference> FindReferencesOfSymbol(
            SymbolReference foundSymbol,
            ScriptFile[] referencedFiles,
            WorkspaceService workspace)
        {
            if (foundSymbol == null)
            {
                return(null);
            }

            // NOTE: we use to make sure aliases were loaded but took it out because we needed the pipeline thread.

            // We want to look for references first in referenced files, hence we use ordered dictionary
            // TODO: File system case-sensitivity is based on filesystem not OS, but OS is a much cheaper heuristic
            var fileMap = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
                ? new OrderedDictionary()
                : new OrderedDictionary(StringComparer.OrdinalIgnoreCase);

            foreach (ScriptFile scriptFile in referencedFiles)
            {
                fileMap[scriptFile.FilePath] = scriptFile;
            }

            foreach (string filePath in workspace.EnumeratePSFiles())
            {
                if (!fileMap.Contains(filePath))
                {
                    if (!workspace.TryGetFile(filePath, out ScriptFile scriptFile))
                    {
                        // If we can't access the file for some reason, just ignore it
                        continue;
                    }

                    fileMap[filePath] = scriptFile;
                }
            }

            var symbolReferences = new List <SymbolReference>();

            foreach (object fileName in fileMap.Keys)
            {
                var file = (ScriptFile)fileMap[fileName];

                IEnumerable <SymbolReference> references = AstOperations.FindReferencesOfSymbol(
                    file.ScriptAst,
                    foundSymbol,
                    needsAliases: false);

                foreach (SymbolReference reference in references)
                {
                    try
                    {
                        reference.SourceLine = file.GetLine(reference.ScriptRegion.StartLineNumber);
                    }
                    catch (ArgumentOutOfRangeException e)
                    {
                        reference.SourceLine = string.Empty;
                        _logger.LogException("Found reference is out of range in script file", e);
                    }
                    reference.FilePath = file.FilePath;
                    symbolReferences.Add(reference);
                }
            }

            return(symbolReferences);
        }
コード例 #30
0
ファイル: Visitor.cs プロジェクト: archfrog/Braceless0
 public virtual object Visit(SymbolReference that, object value)
 {
     throw new System.NotImplementedException();
 }
コード例 #31
0
 /// <summary>
 /// Constructs an instance of a GetDefinitionResut
 /// </summary>
 /// <param name="symRef">The symbolRefernece for the found definition</param>
 public GetDefinitionResult(SymbolReference symRef)
 {
     FoundDefinition = symRef;
 }
コード例 #32
0
ファイル: Variable.cs プロジェクト: laurentprudhon/TypeCobol
 public SymbolReferenceVariable(StorageDataType symbolType, SymbolReference symbolReference)
     : base(symbolType, null)
 {
     SymbolReference = symbolReference;
 }
コード例 #33
0
ファイル: Variable.cs プロジェクト: laurentprudhon/TypeCobol
 public VariableOrExpression(SymbolReference symbolReference)
     : base(symbolReference)
 {
 }
コード例 #34
0
ファイル: Variable.cs プロジェクト: laurentprudhon/TypeCobol
 public Variable(SymbolReference reference)
     : base(StorageDataType.Any, null)
 {
     SymbolReference = reference;
 }
コード例 #35
0
        private string GetDecoratedSymbolName(SymbolReference symbolReference)
        {
            string name = symbolReference.SymbolName;

            if (symbolReference.SymbolType == SymbolType.Configuration ||
                symbolReference.SymbolType == SymbolType.Function ||
                symbolReference.SymbolType == SymbolType.Workflow)
            {
                name += " { }";
            }

            return name;
        }
コード例 #36
0
        /// <summary>
        /// Take a codelens and create a new codelens object with updated references.
        /// </summary>
        /// <param name="codeLens">The old code lens to get updated references for.</param>
        /// <returns>A new code lens object describing the same data as the old one but with updated references.</returns>
        public CodeLens ResolveCodeLens(CodeLens codeLens, ScriptFile scriptFile)
        {
            ScriptFile[] references = _workspaceService.ExpandScriptReferences(
                scriptFile);

            SymbolReference foundSymbol = _symbolsService.FindFunctionDefinitionAtLocation(
                scriptFile,
                codeLens.Range.Start.Line + 1,
                codeLens.Range.Start.Character + 1);

            List <SymbolReference> referencesResult = _symbolsService.FindReferencesOfSymbol(
                foundSymbol,
                references,
                _workspaceService);

            Location[] referenceLocations;
            if (referencesResult == null)
            {
                referenceLocations = s_emptyLocationArray;
            }
            else
            {
                var acc = new List <Location>();
                foreach (SymbolReference foundReference in referencesResult)
                {
                    if (IsReferenceDefinition(foundSymbol, foundReference))
                    {
                        continue;
                    }

                    DocumentUri uri = DocumentUri.From(foundReference.FilePath);
                    // For any vscode-notebook-cell, we need to ignore the backing file on disk.
                    if (uri.Scheme == "file" &&
                        scriptFile.DocumentUri.Scheme == "vscode-notebook-cell" &&
                        uri.Path == scriptFile.DocumentUri.Path)
                    {
                        continue;
                    }

                    acc.Add(new Location
                    {
                        Uri   = uri,
                        Range = foundReference.ScriptRegion.ToRange()
                    });
                }
                referenceLocations = acc.ToArray();
            }

            return(new CodeLens
            {
                Data = codeLens.Data,
                Range = codeLens.Range,
                Command = new Command
                {
                    Name = "editor.action.showReferences",
                    Title = GetReferenceCountHeader(referenceLocations.Length),
                    Arguments = JArray.FromObject(new object[]
                    {
                        scriptFile.DocumentUri,
                        codeLens.Range.Start,
                        referenceLocations
                    },
                                                  LspSerializer.Instance.JsonSerializer)
                }
            });
        }