コード例 #1
0
        protected override void BuildCompletionDataInternal(IEditorData Editor, char enteredChar)
        {
            ed   = Editor;
            ctxt = ResolutionContext.Create(Editor, false);

            AbstractType t = null;

            CodeCompletion.DoTimeoutableCompletionTask(CompletionDataGenerator, ctxt, () =>
            {
                ctxt.Push(Editor);
                if (AccessExpression is IExpression)
                {
                    t = ExpressionTypeEvaluation.EvaluateType(AccessExpression as IExpression, ctxt);
                }
                else if (AccessExpression is ITypeDeclaration)
                {
                    t = TypeDeclarationResolver.ResolveSingle(AccessExpression as ITypeDeclaration, ctxt);
                }
            });

            if (t == null)             //TODO: Add after-space list creation when an unbound . (Dot) was entered which means to access the global scope
            {
                return;
            }

            t.Accept(this);
        }
コード例 #2
0
        protected override void BuildCompletionDataInternal(IEditorData Editor, char enteredChar)
        {
            var ctxt = ResolutionContext.Create(Editor, false);

            foreach (var kv in VersionCompletionItems)
            {
                CompletionDataGenerator.AddTextItem(kv.Key, kv.Value);
            }

            CodeCompletion.DoTimeoutableCompletionTask(CompletionDataGenerator, ctxt, () => {
                ctxt.Push(Editor);
                var cs = ctxt.CurrentContext.DeclarationCondititons;
                foreach (var v in cs.GlobalFlags.Versions)
                {
                    if (!VersionCompletionItems.ContainsKey(v))
                    {
                        CompletionDataGenerator.AddTextItem(v, "");
                    }
                }
                foreach (var v in cs.LocalFlags.Versions)
                {
                    if (!VersionCompletionItems.ContainsKey(v))
                    {
                        CompletionDataGenerator.AddTextItem(v, "");
                    }
                }
            });
        }
コード例 #3
0
ファイル: CompletionResults.cs プロジェクト: JadeHub/Jade
        internal unsafe Results(CodeCompletion.Library.CXCodeCompleteResults* handle, TranslationUnit tu)
        {
            Int64 ii = Library.clang_codeCompleteGetContexts(handle);

            _handleToDispose = handle;
            _handle = *handle;
            _results = new List<Result>();

            bool print = _handle.NumberResults <= 100;
            for(uint i = 0;i < _handle.NumberResults; i++)
            {
                //Library.CXCompletionResult r = _handle.Results[i];
                Result r = new Result(_handle.Results[i]);
                _results.Add(r);
                if(print)
                    System.Diagnostics.Debug.WriteLine(r);
            }
            if(!print)
                System.Diagnostics.Debug.WriteLine("too many results");

          /*  List<LibClang.Diagnostic> diags = new List<Diagnostic>();
            for(uint d = 0; d < Library.clang_codeCompleteGetNumDiagnostics(_handleToDispose); d++)
            {
                Diagnostic diag = new Diagnostic(Library.clang_codeCompleteGetDiagnostic(handle, d), tu.ItemFactory);
                
                System.Diagnostics.Debug.WriteLine(diag + " " + diag.Location);
            }*/
        }
コード例 #4
0
ファイル: CompletionTests.cs プロジェクト: Orvid/D_Parser
                public override bool Matches(object actual)
                {
                    var code = actual as string;

                    if (code == null)
                    {
                        return(false);
                    }

                    code += "\n";

                    var m     = DParser.ParseString(code);
                    var cache = ResolutionTests.CreateCache();

                    (cache [0] as MutableRootPackage).AddModule(m);

                    var ed = new EditorData {
                        ModuleCode    = code,
                        CaretOffset   = code.Length - 1,
                        CaretLocation = DocumentHelper.OffsetToLocation(code, code.Length - 1),
                        SyntaxTree    = m,
                        ParseCache    = cache
                    };

                    var gen = new TestCompletionDataGen(null, null);
                    var res = CodeCompletion.GenerateCompletionData(ed, gen, 'a');

                    return(neg ? !res : res);
                }
コード例 #5
0
        public void GetSemanticExpansions(string filename, string tok, uint line, uint idx, string expr)
        {
            filename = normalizePath(filename);
            var ast = GetModule(filename);

            if (ast == null)
            {
                throw new COMException("module not found", 1);
            }

            _setupEditorData();
            CodeLocation loc = new CodeLocation((int)idx + 1, (int)line);

            _editorData.SyntaxTree  = ast as DModule;
            _editorData.ModuleCode  = _sources[filename];
            _editorData.CaretOffset = getCodeOffset(_editorData.ModuleCode, loc);
            // step back to beginning of identifier
            while (_editorData.CaretOffset > 0 && Lexer.IsIdentifierPart(_editorData.ModuleCode[_editorData.CaretOffset - 1]))
            {
                _editorData.CaretOffset--;
                if (idx > 0)
                {
                    idx--;
                }
            }
            _editorData.CaretLocation = new CodeLocation((int)idx + 1, (int)line);

            char triggerChar = string.IsNullOrEmpty(tok) ?  '\0' : tok[0];
            VDServerCompletionDataGenerator cdgen = new VDServerCompletionDataGenerator(tok);

            CodeCompletion.GenerateCompletionData(_editorData, cdgen, triggerChar);

            _expansions = cdgen.expansions;
        }
コード例 #6
0
        public void GetPythonParenCompletions(string source, int line, int column)
        {
            source = HttpUtility.HtmlDecode(source);
            JavaScriptSerializer json = new JavaScriptSerializer();

            HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
            HttpContext.Current.Response.Write(json.Serialize(CodeCompletion.GetPythonParenCompletion(source, line, column)));
        }
コード例 #7
0
        protected override IEnumerable <Ide.FindInFiles.MemberReference> GetReferences(Tuple <ResolutionContext, DSymbol> tup, System.Threading.CancellationToken token)
        {
            var ctxt = tup.Item1;

            ctxt.CancellationToken = token;
            var mr = tup.Item2;

            var referencedNode = mr.Definition;

            // Slightly hacky: To keep highlighting the id of e.g. a NewExpression, take the ctor's parent node (i.e. the class node)
            if (referencedNode is DMethod && ((DMethod)referencedNode).SpecialType == DMethod.MethodType.Constructor)
            {
                mr = mr.Base as DSymbol;
                if (mr == null)
                {
                    yield break;
                }
                referencedNode = mr.Definition;
            }

            IEnumerable <ISyntaxRegion> refs = null;

            CodeCompletion.DoTimeoutableCompletionTask(null, ctxt, () => {
                try {
                    refs = D_Parser.Refactoring.ReferencesFinder.SearchModuleForASTNodeReferences(SyntaxTree, referencedNode, ctxt);
                } catch (Exception ex) {
                    LoggingService.LogInfo("Error during highlighting usages", ex);
                }
            });

            if (refs != null)
            {
                foreach (var sr in refs)
                {
                    CodeLocation loc;
                    int          len;
                    if (sr is INode)
                    {
                        loc = (sr as INode).NameLocation;
                        len = (sr as INode).Name.Length;
                    }
                    else if (sr is TemplateParameter)
                    {
                        loc = (sr as TemplateParameter).NameLocation;
                        len = (sr as TemplateParameter).Name.Length;
                    }
                    else
                    {
                        loc = sr.Location;
                        len = sr.EndLocation.Column - loc.Column;
                    }

                    yield return(new Ide.FindInFiles.MemberReference(sr,
                                                                     new ICSharpCode.NRefactory.TypeSystem.DomRegion(Document.FileName, loc.Line, loc.Column, loc.Line, loc.Column + len),
                                                                     Document.Editor.LocationToOffset(loc.Line, loc.Column), len));
                }
            }
        }
コード例 #8
0
ファイル: CompletionTests.cs プロジェクト: Orvid/D_Parser
        public static TestCompletionDataGen TestCompletionListContents(IEditorData ed, INode[] itemWhiteList = null, INode[] itemBlackList = null, char trigger = '\0')
        {
            var gen = new TestCompletionDataGen(itemWhiteList, itemBlackList);

            Assert.That(CodeCompletion.GenerateCompletionData(ed, gen, trigger), Is.True);

            Assert.That(gen.HasRemainingItems, Is.False, "Some items were not enlisted!");
            return(gen);
        }
コード例 #9
0
        void OnCodeCompletion(object sender, ExecutedRoutedEventArgs e)
        {
            CompletionWindow?.Close();


            if (CodeCompletion != null && CodeCompletion.CtrlSpace(this))
            {
                e.Handled = true;
            }
        }
コード例 #10
0
        public static void BuildCompletionData(Document EditorDocument,
                                               DModule SyntaxTree,
                                               CodeCompletionContext ctx,
                                               CompletionDataList l,
                                               char triggerChar)
        {
            var ed = DResolverWrapper.CreateEditorData(EditorDocument, SyntaxTree, ctx, triggerChar);

            CodeCompletion.GenerateCompletionData(ed, new CompletionDataGenerator(l, null), triggerChar);
        }
コード例 #11
0
        public string GetCPPCompletions(string source, int line, int column)
        {
            source = Decompress(source);
            //HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
            var res = CodeCompletion.GetCPP_Completions(source, line, column);
            JavaScriptSerializer json = new JavaScriptSerializer();
            var s = json.Serialize(res);

            return(Compress(s));
        }
コード例 #12
0
ファイル: CompletionTests.cs プロジェクト: Orvid/D_Parser
        public void AutoCompletion()
        {
            var code = @"module A;
void main() {
auto 
}";
            var ed   = GenEditorData(3, 5, code);
            var g    = new TestCompletionDataGen(null, null);

            Assert.That(CodeCompletion.GenerateCompletionData(ed, g, 'a', true), Is.False);
        }
コード例 #13
0
ファイル: CompletionTests.cs プロジェクト: Orvid/D_Parser
        public void ForeachCompletion()
        {
            var code = @"module A;
void main() {
foreach( 
}";
            var ed   = GenEditorData(3, 9, code);
            var g    = new TestCompletionDataGen(null, null);

            Assert.That(CodeCompletion.GenerateCompletionData(ed, g, 'a', true), Is.True);
        }
コード例 #14
0
 void GenUfcsAndStaticProperties(AbstractType t)
 {
     if (t.NonStaticAccess && CompletionOptions.Instance.ShowUFCSItems)
     {
         CodeCompletion.DoTimeoutableCompletionTask(null, ctxt, () =>
         {
             foreach (var ufcsItem in UFCSResolver.TryResolveUFCS(t, 0, ed.CaretLocation, ctxt))
             {
                 CompletionDataGenerator.Add((ufcsItem as DSymbol).Definition);
             }
         });
     }
     StaticProperties.ListProperties(CompletionDataGenerator, ctxt, MemberFilter, t, t.NonStaticAccess);
 }
コード例 #15
0
ファイル: CompletionTests.cs プロジェクト: Orvid/D_Parser
        public void NonStaticCompletion1()
        {
            var code = @"module A;
struct SomeStruct {ubyte a; static void read() {

}}
";
            var ed   = GenEditorData(3, 1, code);

            var SomeStruct = (ed.ParseCache [0] ["A"] ["SomeStruct"].First() as DClassLike);
            var a          = SomeStruct["a"].First() as DVariable;
            var read       = SomeStruct ["read"].First() as DMethod;
            var g          = new TestCompletionDataGen(new[] { read }, new[] { a });

            Assert.That(CodeCompletion.GenerateCompletionData(ed, g, '\0', true), Is.True);
        }
コード例 #16
0
ファイル: CompletionTests.cs プロジェクト: Orvid/D_Parser
        public void ForeachIteratorCompletion()
        {
            var code = @"module A;
void main() {Cl** ii;
foreach(i;ii)
i.
}

struct Cl { int a; }
";
            var ed   = GenEditorData(4, 3, code);

            var a = (ed.ParseCache[0]["A"]["Cl"].First() as DClassLike)["a"].First() as DVariable;

            var g = new TestCompletionDataGen(new[] { a }, null);

            Assert.That(CodeCompletion.GenerateCompletionData(ed, g, 'a', true), Is.True);
        }
コード例 #17
0
ファイル: TypeReferenceFinder.cs プロジェクト: Orvid/D_Parser
        public static Dictionary <int, Dictionary <ISyntaxRegion, byte> > Scan(IEditorData ed, List <ISyntaxRegion> invalidConditionalCodeRegions = null, int timeout = int.MinValue)
        {
            if (ed == null || ed.SyntaxTree == null)
            {
                return(new Dictionary <int, Dictionary <ISyntaxRegion, byte> >());
            }

            var ctxt = ResolutionContext.Create(ed, false);

            // Since it's just about enumerating, not checking types, ignore any conditions
            ctxt.ContextIndependentOptions |= ResolutionOptions.IgnoreDeclarationConditions;

            var typeRefFinder = new TypeReferenceFinder(ctxt, invalidConditionalCodeRegions);

            CodeCompletion.DoTimeoutableCompletionTask(null, ctxt, () => ed.SyntaxTree.Accept(typeRefFinder), timeout);

            return(typeRefFinder.Matches);
        }
コード例 #18
0
        void TextArea_TextEntering(object sender, TextCompositionEventArgs e)
        {
            if (CompletionWindow != null || CodeCompletion == null)
            {
                return;
            }

            if (e.Handled)
            {
                return;
            }

            foreach (var c in e.Text)
            {
                var result = CodeCompletion.HandleKeyPress(this, c);
                if (result == CodeCompletionKeyPressResult.Completed)
                {
                    if (CompletionWindow != null)
                    {
                        // a new CompletionWindow was shown, but does not eat the input
                        // tell it to expect the text insertion
                        CompletionWindow.ExpectInsertionBeforeStart = true;
                    }
                    return;
                }
                else if (result == CodeCompletionKeyPressResult.CompletedIncludeKeyInCompletion)
                {
                    if (CompletionWindow != null && CompletionWindow?.StartOffset == CompletionWindow.EndOffset)
                    {
                        CompletionWindow.CloseWhenCaretAtBeginning = true;
                    }
                    return;
                }
                else if (result == CodeCompletionKeyPressResult.EatKey)
                {
                    e.Handled = true;
                    return;
                }
            }
        }
コード例 #19
0
        protected override string Process(EditorData editorData, string tok)
        {
            var originalCaretLocation = editorData.CaretLocation;
            var idx = originalCaretLocation.Column - 1;

            // step	back to	beginning of identifier
            while (editorData.CaretOffset > 0 && Lexer.IsIdentifierPart(editorData.ModuleCode[editorData.CaretOffset - 1]))
            {
                editorData.CaretOffset--;
                if (idx > 0)
                {
                    idx--;
                }
            }
            editorData.CaretLocation = new CodeLocation(idx + 1, originalCaretLocation.Line);

            char triggerChar = string.IsNullOrEmpty(tok) ? '\0' : tok[0];

            var cdgen = new VDServerCompletionDataGenerator(tok);

            CodeCompletion.GenerateCompletionData(editorData, cdgen, triggerChar);
            return(cdgen.expansions.ToString());
        }
コード例 #20
0
        public override Task <CompletionList> Handle(CompletionParams request, CancellationToken cancellationToken)
        {
            var ed       = CreateCompletionEditorData(request, cancellationToken, out char triggerChar);
            var workDone = ProgressManager.WorkDone(request,
                                                    new WorkDoneProgressBegin {
                Message = "Begin generating completion info", Percentage = 0
            });
            var progress = ProgressManager.For(request, cancellationToken);

            var allResults = new List <CompletionItem>();

            var completionDataGenerator = new CompletionDataGeneratorImpl(item =>
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                allResults.Add(item);
                if (allResults.Count % 15 == 0)
                {
                    progress?.OnNext(new CompletionList(allResults));
                }
            });

            CodeCompletion.GenerateCompletionData(ed, completionDataGenerator, triggerChar);

            if (cancellationToken.IsCancellationRequested)
            {
                return(Task.FromCanceled <CompletionList>(cancellationToken));
            }
            workDone.OnCompleted();
            progress?.OnNext(new CompletionList(allResults));
            progress?.OnCompleted();

            return(Task.FromResult(progress != null ? new CompletionList() : new CompletionList(allResults)));
        }
コード例 #21
0
        public static AbstractType ResolveType(IEditorData editor, ResolutionContext ctxt = null)
        {
            var o = GetScopedCodeObject(editor);

            if (ctxt == null)
            {
                ctxt = ResolutionContext.Create(editor, false);
            }

            AbstractType ret = null;

            CodeCompletion.DoTimeoutableCompletionTask(null, ctxt, () =>
            {
                ctxt.Push(editor);

                var optionBackup = ctxt.CurrentContext.ContextDependentOptions;
                ctxt.CurrentContext.ContextDependentOptions |= ResolutionOptions.ReturnMethodReferencesOnly;

                if (o is IExpression)
                {
                    ret = ExpressionTypeEvaluation.EvaluateType((IExpression)o, ctxt, false);
                }
                else if (o is ITypeDeclaration)
                {
                    ret = TypeDeclarationResolver.ResolveSingle((ITypeDeclaration)o, ctxt);
                }
                else if (o is INode)
                {
                    ret = TypeDeclarationResolver.HandleNodeMatch(o as INode, ctxt);
                }

                ctxt.CurrentContext.ContextDependentOptions = optionBackup;
            });

            return(ret);
        }
		public override Task<CodeCompletion.ICompletionDataList> CodeCompletionCommand (CodeCompletion.CodeCompletionContext completionContext)
		{
			if (!IsActiveExtension()) return null;
			return completionTextEditorExtension.CodeCompletionCommand (completionContext);
		}
		public override CodeCompletion.ICompletionDataList ShowCodeSurroundingsCommand (CodeCompletion.CodeCompletionContext completionContext)
		{
			if (!IsActiveExtension()) return null;
			return completionTextEditorExtension.ShowCodeSurroundingsCommand (completionContext);
		}
		public override System.Threading.Tasks.Task<CodeCompletion.ParameterHintingResult> HandleParameterCompletionAsync (CodeCompletion.CodeCompletionContext completionContext, char completionChar, System.Threading.CancellationToken token)
		{
			return completionTextEditorExtension.HandleParameterCompletionAsync (completionContext, completionChar, token);
		}
		public override System.Threading.Tasks.Task<CodeCompletion.ICompletionDataList> HandleCodeCompletionAsync (CodeCompletion.CodeCompletionContext completionContext, char completionChar, System.Threading.CancellationToken token)
		{
			return completionTextEditorExtension.HandleCodeCompletionAsync (completionContext, completionChar, token);
		}
コード例 #26
0
        /// <summary>
        /// Formats the intellisence popup description with the colour syntax of the current entry.
        /// </summary>
        /// <returns></returns>
        private object RenderDescription()
        {
            var rowNumber = 0;

            CodeCompletion.InvokePreviewInstantHelp(new InstantHelpEventArgs {
                HtmlHelp     = Entry.LongDescription,
                HtmlExamples = Entry.Examples.Select(e => new InstantHelpEventArgs.HtmlExample {
                    Description          = e.Description,
                    Code                 = e.Code,
                    Css                  = e.Css,
                    Html                 = e.Html,
                    JavascriptReferences = e.JavascriptReferences.ToList()
                }).ToList()
            });

            var grid = new Grid();

            foreach (var signature in Entry.Signatures)
            {
                var member = new TextBlock();
                grid.RowDefinitions.Add(new RowDefinition());
                Grid.SetRow(member, rowNumber++);

                if (Entry.Type == MemberType.TemplateTag)
                {
                    // Templates don't have all the extra member syntax to render
                    member.Inlines.Add(new Run(Text)
                    {
                        Foreground = Brushes.Black, FontWeight = FontWeights.Bold
                    });
                }
                else
                {
                    if (Entry.Type == MemberType.Method || Entry.Type == MemberType.Property)
                    {
                        member.Inlines.Add(new Run(Entry.ReturnType + " ")
                        {
                            Foreground = Brushes.Green
                        });
                    }
                    member.Inlines.Add(new Run(Text)
                    {
                        Foreground = Brushes.Black, FontWeight = FontWeights.Bold
                    });
                    member.Inlines.Add(new Run("(")
                    {
                        Foreground = Brushes.Black
                    });

                    var renderedFirst = false;
                    foreach (var argument in signature.Arguments)
                    {
                        if (renderedFirst)
                        {
                            member.Inlines.Add(new Run(", "));
                        }
                        renderedFirst = true;

                        if (argument.Optional)
                        {
                            member.Inlines.Add(new Run("["));
                        }
                        if (argument.Type.ToLower() == "function")
                        {
                            member.Inlines.Add(new Run("function ")
                            {
                                Foreground = Brushes.Green
                            });
                        }
                        member.Inlines.Add(new Run(argument.Name));
                        if (argument.Optional)
                        {
                            member.Inlines.Add(new Run("]"));
                        }
                    }
                    member.Inlines.Add(new Run(")")
                    {
                        Foreground = Brushes.Black
                    });
                }
                grid.Children.Add(member);

                foreach (var argument in signature.Arguments)
                {
                    member = new TextBlock();
                    grid.RowDefinitions.Add(new RowDefinition());
                    Grid.SetRow(member, rowNumber++);
                    member.Inlines.Add(new Run(argument.Name + ": ")
                    {
                        FontWeight = FontWeights.Bold
                    });
                    member.Inlines.Add(new Run(argument.Description));
                    grid.Children.Add(member);
                }
            }

            grid.RowDefinitions.Add(new RowDefinition());
            grid.Children.Add(CreateTextBlock(Entry.Description, Brushes.Green, FontWeights.Normal, rowNumber++));

            return(grid);
        }
 	public static void AddMemberBeforeDot(CodeCompletion.SymScope sc)
 	{
 		cur_sc = sc;
 	}
コード例 #28
0
 private string construct_header(string meth, CodeCompletion.ProcScope ps, int tabCount)
 {
     //if (CodeCompletion.CodeCompletionController.currentParser != null)
     return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.ConstructHeader(meth, ps, tabCount);
 }
コード例 #29
0
        public ObjectValue Resolve(ulong offset, string symbolname, string typename, string val, DEW.DebugScopedSymbol parentsymbol)
        {
            DModule module;
            int     codeLine;
            INode   variableNode = null;

            // Search currently scoped module
            string file = "";
            uint   line = 0;

            Engine.Symbols.GetLineByOffset(Engine.CurrentInstructionOffset, out file, out line);
            codeLine = (int)line;

            if (string.IsNullOrWhiteSpace(file))
            {
                return(null);
            }

            AbstractDProject dproj = null;

            module = GetFileSyntaxTree(file, out dproj);

            // If syntax tree built, search the variable location
            if (module != null)
            {
                var ed   = Resolver.DResolverWrapper.CreateEditorData(IdeApp.Workbench.ActiveDocument);
                var ctxt = ResolutionContext.Create(ed, false);

                CodeCompletion.DoTimeoutableCompletionTask(null, ctxt, () =>
                {
                    var loc = new CodeLocation(0, codeLine);
                    ctxt.Push(DResolver.SearchBlockAt(module, loc), loc);

                    AbstractType[] res;
                    if (parentsymbol != null)
                    {
                        var parentres = ResolveParentSymbol(parentsymbol, ctxt);
                        res           = TypeDeclarationResolver.ResolveFurtherTypeIdentifier(symbolname, parentres, ctxt, null);
                    }
                    else
                    {
                        res = TypeDeclarationResolver.ResolveIdentifier(symbolname, ctxt, null);
                    }

                    if (res != null && res.Length > 0 && res[0] is DSymbol)
                    {
                        variableNode = (res[0] as DSymbol).Definition;
                    }
                });
            }

            // Set type string
            string _typeString = typename;

            if (variableNode != null)
            {
                var t = variableNode.Type;
                if (t != null)
                {
                    _typeString = t.ToString();
                }
            }

            // Set value string
            string _valueString = val;

            ObjectValueFlags flags = ObjectValueFlags.Variable;

            if (variableNode != null)
            {
                ITypeDeclaration curValueType = variableNode.Type;
                if (curValueType != null)
                {
                    if (!IsBasicType(curValueType))
                    {
                        if (_typeString == "string")                         //TODO: Replace this by searching the alias definition in the cache
                        {
                            curValueType = new ArrayDecl()
                            {
                                InnerDeclaration = new DTokenDeclaration(DTokens.Char)
                            }
                        }
                        ;
                        else if (_typeString == "wstring")
                        {
                            curValueType = new ArrayDecl()
                            {
                                InnerDeclaration = new DTokenDeclaration(DTokens.Wchar)
                            }
                        }
                        ;
                        else if (_typeString == "dstring")
                        {
                            curValueType = new ArrayDecl()
                            {
                                InnerDeclaration = new DTokenDeclaration(DTokens.Dchar)
                            }
                        }
                        ;

                        if (IsArray(curValueType))
                        {
                            flags = ObjectValueFlags.Array;

                            var clampDecl = curValueType as ArrayDecl;
                            var valueType = clampDecl.InnerDeclaration;

                            if (valueType is DTokenDeclaration)
                            {
                                bool IsString = false;
                                uint elsz     = 0;
                                var  realType = DetermineArrayType((valueType as DTokenDeclaration).Token, out elsz, out IsString);

                                var arr = Engine.Symbols.ReadArray(offset, realType, elsz);

                                if (arr != null)
                                {
                                    _valueString = BuildArrayContentString(arr, IsString);
                                }
                            }
                        }
                        else
                        {
                            flags = ObjectValueFlags.Object;
                        }
                    }
                }
            }

            return(ObjectValue.CreatePrimitive(ObjectValueSource, new ObjectPath(symbolname), _typeString, new EvaluationResult(_valueString), flags));
        }
コード例 #30
0
        public static AbstractType ResolveTypeLoosely(IEditorData editor, out NodeResolutionAttempt resolutionAttempt, ResolutionContext ctxt = null)
        {
            var o = GetScopedCodeObject(editor);

            if (ctxt == null)
            {
                ctxt = ResolutionContext.Create(editor, false);
            }

            AbstractType          ret        = null;
            NodeResolutionAttempt resAttempt = NodeResolutionAttempt.Normal;

            CodeCompletion.DoTimeoutableCompletionTask(null, ctxt, () =>
            {
                ctxt.Push(editor);

                var optionBackup = ctxt.CurrentContext.ContextDependentOptions;
                ctxt.CurrentContext.ContextDependentOptions |= ResolutionOptions.ReturnMethodReferencesOnly | ResolutionOptions.DontResolveAliases;

                if (o is IExpression)
                {
                    ret = ExpressionTypeEvaluation.EvaluateType((IExpression)o, ctxt, false);
                }
                else if (o is ITypeDeclaration)
                {
                    ret = TypeDeclarationResolver.ResolveSingle((ITypeDeclaration)o, ctxt);
                }
                else if (o is INode)
                {
                    ret = TypeDeclarationResolver.HandleNodeMatch(o as INode, ctxt, null, o);
                }
                else
                {
                    ret = null;
                }

                if (ret == null)
                {
                    resAttempt = NodeResolutionAttempt.NoParameterOrTemplateDeduction;

                    if (o is PostfixExpression_MethodCall)
                    {
                        o = (o as PostfixExpression_MethodCall).PostfixForeExpression;
                    }

                    ctxt.CurrentContext.ContextDependentOptions |= ResolutionOptions.NoTemplateParameterDeduction | ResolutionOptions.DontResolveAliases;

                    if (o is IdentifierExpression)
                    {
                        ret = AmbiguousType.Get(ExpressionTypeEvaluation.GetOverloads(o as IdentifierExpression, ctxt, deduceParameters: false), o);
                    }
                    else if (o is ITypeDeclaration)
                    {
                        ret = TypeDeclarationResolver.ResolveSingle(o as ITypeDeclaration, ctxt);
                    }
                    else if (o is IExpression)
                    {
                        ret = ExpressionTypeEvaluation.EvaluateType(o as IExpression, ctxt, false);
                    }
                }

                if (ret == null)
                {
                    resAttempt    = NodeResolutionAttempt.RawSymbolLookup;
                    var overloads = TypeDeclarationResolver.HandleNodeMatches(LookupIdRawly(editor, o as ISyntaxRegion), ctxt, null, o);
                    ret           = AmbiguousType.Get(overloads, o);
                }

                ctxt.CurrentContext.ContextDependentOptions = optionBackup;
            });

            resolutionAttempt = resAttempt;

            if (ret != null)
            {
                ret.DeclarationOrExpressionBase = o;
            }

            return(ret);
        }
コード例 #31
0
        public async Task <IActionResult> GetCompletion(string code)
        {
            var data = await CodeCompletion.Run(code, code.Length - 1);

            return(Ok(data));
        }
		public override Task<CodeCompletion.ParameterHintingResult> ParameterCompletionCommand (CodeCompletion.CodeCompletionContext completionContext)
		{
			if (!IsActiveExtension()) return null;
			return completionTextEditorExtension.ParameterCompletionCommand (completionContext);
		}
		public override Task<int> GuessBestMethodOverload (CodeCompletion.ParameterHintingResult provider, int currentOverload, System.Threading.CancellationToken token)
		{
			if (!IsActiveExtension()) return Task.FromResult (-1);
			return completionTextEditorExtension.GuessBestMethodOverload (provider, currentOverload, token);
		}
		public override int GuessBestMethodOverload (CodeCompletion.ParameterHintingResult provider, int currentOverload)
		{
			if (!IsActiveExtension()) return -1;
			return completionTextEditorExtension.GuessBestMethodOverload (provider, currentOverload);
		}
コード例 #35
0
        public void Completion_Grammar_SimpleExpression()
        {
            // arrange
            var input       = "var c = a + b()";
            var inputStream = new AntlrInputStream(input);
            var lexer       = new ExprLexer(inputStream);
            var tokenStream = new CommonTokenStream(lexer);
            var parser      = new ExprParser(tokenStream);

            lexer.RemoveErrorListeners();
            parser.RemoveErrorListeners();

            var errorListener = new CountingErrorListener();

            parser.AddErrorListener(errorListener);

            // act
            // assert

            // Specify our entry point
            var tree = parser.expression();

            Check.That(errorListener.ErrorCount).IsEqualTo(0);

            var core = new CodeCompletion(parser, null, null);

            // 1) At the input start.
            var candidates = core.CollectCandidates(0, null);

            Check.That(candidates.Tokens).HasSize(3);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.VAR);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.LET);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.ID);

            Check.That(candidates.Tokens[ExprLexer.VAR]).IsEqualTo(new[] { ExprLexer.ID, ExprLexer.EQUAL });
            Check.That(candidates.Tokens[ExprLexer.LET]).IsEqualTo(new[] { ExprLexer.ID, ExprLexer.EQUAL });
            Check.That(candidates.Tokens[ExprLexer.ID]).HasSize(0);

            // 2) On the first whitespace. In real implementations you would do some additional checks where in the whitespace
            //    the caret is, as the outcome is different depending on that position.
            candidates = core.CollectCandidates(1, null);
            Check.That(candidates.Tokens).HasSize(1);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.ID);

            // 3) On the variable name ('c').
            candidates = core.CollectCandidates(2, null);
            Check.That(candidates.Tokens).HasSize(1);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.ID);

            // 4) On the equal sign (ignoring whitespace positions from now on).
            candidates = core.CollectCandidates(4, null);
            Check.That(candidates.Tokens).HasSize(1);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.EQUAL);

            // 5) On the variable reference 'a'. But since we have not configure the c3 engine to return us var refs
            //    (or function refs for that matter) we only get an ID here.
            candidates = core.CollectCandidates(6, null);
            Check.That(candidates.Tokens).HasSize(1);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.ID);

            // 6) On the '+' operator. Usually you would not show operators as candidates, but we have not set up the c3 engine
            //    yet to not return them.
            candidates = core.CollectCandidates(8, null);
            Check.That(candidates.Tokens).HasSize(5);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.PLUS);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.MINUS);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.MULTIPLY);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.DIVIDE);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.OPEN_PAR);
        }
コード例 #36
0
 private string construct_header(CodeCompletion.ProcRealization ps, int tabCount)
 {
     return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.ConstructHeader(ps, tabCount);
 }
コード例 #37
0
        public void Completion_Grammar_TypicalExpression()
        {
            // arrange
            var expression  = "var c = a + b";
            var inputStream = new AntlrInputStream(expression);
            var lexer       = new ExprLexer(inputStream);
            var tokenStream = new CommonTokenStream(lexer);
            var parser      = new ExprParser(tokenStream);

            parser.Interpreter.PredictionMode = PredictionMode.LL_EXACT_AMBIG_DETECTION;

            lexer.RemoveErrorListeners();
            parser.RemoveErrorListeners();

            var errorListener = new CountingErrorListener();

            parser.AddErrorListener(errorListener);

            // act
            // assert

            // Specify our entry point
            var tree = parser.expression();

            Check.That(errorListener.ErrorCount).IsEqualTo(0);

            // Tell the engine to return certain rules to us, which we could use to look up values in a symbol table.
            var preferredRules = new HashSet <int>()
            {
                ExprParser.RULE_functionRef, ExprParser.RULE_variableRef
            };

            // Ignore operators and the generic ID token.
            var ignoredTokens = new HashSet <int>()
            {
                ExprLexer.PLUS, ExprLexer.MINUS,
                ExprLexer.MULTIPLY, ExprLexer.DIVIDE
            };

            var core = new CodeCompletion(parser, preferredRules, ignoredTokens);

            // 1) At the input start.
            var candidates = core.CollectCandidates(0, null);

            Check.That(candidates.Tokens).HasSize(2);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.VAR);
            Check.That(candidates.Tokens).ContainsKey(ExprLexer.LET);

            Check.That(candidates.Tokens
                       .TryGetValue(ExprLexer.VAR, out var varCandidates))
            .IsTrue();
            Check.That(candidates.Tokens
                       .TryGetValue(ExprLexer.LET, out var letCandidates))
            .IsTrue();

            Check.That(varCandidates).HasSize(2);
            Check.That(letCandidates).HasSize(2);

            Check.That(varCandidates).IsEqualTo(new[] { ExprLexer.ID, ExprLexer.EQUAL });
            Check.That(letCandidates).IsEqualTo(new[] { ExprLexer.ID, ExprLexer.EQUAL });

            // 2) On the variable name ('c').
            ignoredTokens = new HashSet <int>()
            {
                ExprLexer.ID, ExprLexer.PLUS, ExprLexer.MINUS,
                ExprLexer.MULTIPLY, ExprLexer.DIVIDE, ExprLexer.EQUAL
            };
            core       = new CodeCompletion(parser, preferredRules, ignoredTokens);
            candidates = core.CollectCandidates(2, null);
            Check.That(candidates.Tokens).HasSize(0);

            // 4) On the equal sign (ignoring whitespace positions from now on).
            candidates = core.CollectCandidates(4, null);
            Check.That(candidates.Tokens).HasSize(0);

            // 5) On the variable reference 'a'.
            candidates = core.CollectCandidates(6, null);
            Check.That(candidates.Tokens).HasSize(0);
            Check.That(candidates.Rules).HasSize(2);

            // Here we get 2 rule indexes, derived from 2 different IDs possible at this caret position.
            // These are what we told the engine above to be preferred rules for us.
            var found = 0;

            foreach (var candidate in candidates.Rules)
            {
                switch (candidate.Key)
                {
                case ExprParser.RULE_functionRef:
                {
                    found++;
                    break;
                }

                case ExprParser.RULE_variableRef:
                {
                    found++;
                    break;
                }
                }
            }

            Check.That(found).Equals(2);

            // 6) On the whitespace after the 'a'
            candidates = core.CollectCandidates(7, null);
            Check.That(candidates.Tokens).HasSize(0);
            Check.That(candidates.Rules).HasSize(1);

            // Here we get 2 rule indexes
            found = 0;
            foreach (var candidate in candidates.Rules)
            {
                switch (candidate.Key)
                {
                case ExprParser.RULE_functionRef:
                {
                    found++;
                    break;
                }

                case ExprParser.RULE_variableRef:
                {
                    found++;
                    break;
                }
                }
            }

            Check.That(found).Equals(1);
        }
 	public static string GetRecentUsedMember(CodeCompletion.SymScope sc)
 	{
 		return ht[sc.GetFullName()] as string;
 	}
コード例 #39
0
ファイル: FileProcessingData.cs プロジェクト: Orvid/D_Parser
        public void Process()
        {
            try
            {
                str               = File.ReadAllText(FullFilePath);
                this.FileLength   = str.Length;
                this.lengthString = this.FileLength.ToString();
                int line      = 1;
                int lineStart = 0;

                while (i <= str.Length)
                {
                    if (i < str.Length)
                    {
                        while (i < str.Length)
                        {
                            switch (str[i])
                            {
                            case ' ':
                            case '\t':
                                i++;
                                while (i < str.Length && (str[i] == ' ' || str[i] == '\t'))
                                {
                                    i++;
                                }
                                goto BreakLoop;

                            case '\n':
                                line++;
                                lineStart = i + 1;
                                i++;
                                continue;

                            case '"':
                                // Basic string
                                i++;
                                while (i < str.Length && str[i] != '"')
                                {
                                    if (str[i] == '\\')
                                    {
                                        i++;
                                    }
                                    i++;
                                }
                                i++;
                                goto BreakLoop;

                            case '/':
                                if (i + 1 >= str.Length)
                                {
                                    goto default;
                                }
                                if (str[i + 1] == '/')
                                {
                                    // Line Comment
                                    i += 2;
                                    while (i < str.Length && str[i] != '\n')
                                    {
                                        i++;
                                    }
                                    goto BreakLoop;
                                }
                                else if (str[i + 1] == '*')
                                {
                                    // Block Comment
                                    i += 2;
                                    while (i < str.Length)
                                    {
                                        if (str[i] == '*' && i + 1 < str.Length && str[i + 1] == '/')
                                        {
                                            i += 2;
                                            break;
                                        }
                                        else if (str[i] == '\n')
                                        {
                                            line++;
                                            lineStart = i + 1;
                                        }
                                        i++;
                                    }
                                    goto BreakLoop;
                                }
                                else if (str[i + 1] == '+')
                                {
                                    // Nesting Block Comment
                                    i += 2;
                                    int nestDepth = 1;
                                    while (i < str.Length)
                                    {
                                        if (str[i] == '+' && i + 1 < str.Length && str[i + 1] == '/')
                                        {
                                            i++;
                                            nestDepth--;
                                            if (nestDepth == 0)
                                            {
                                                i++;
                                                break;
                                            }
                                        }
                                        else if (str[i] == '/' && i + 1 < str.Length && str[i + 1] == '+')
                                        {
                                            i++;
                                            nestDepth++;
                                        }
                                        else if (str[i] == '\n')
                                        {
                                            line++;
                                            lineStart = i + 1;
                                        }
                                        i++;
                                    }
                                    goto BreakLoop;
                                }
                                goto default;

                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                i++;
                                while (i < str.Length && IsDigit(str[i]))
                                {
                                    i++;
                                }
                                goto BreakLoop;

                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                            case 'g':
                            case 'h':
                            case 'i':
                            case 'j':
                            case 'k':
                            case 'l':
                            case 'm':
                            case 'n':
                            case 'o':
                            case 'p':
                            case 'q':
                            case 'r':
                            case 's':
                            case 't':
                            case 'u':
                            case 'v':
                            case 'w':
                            case 'x':
                            case 'y':
                            case 'z':
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                            case 'G':
                            case 'H':
                            case 'I':
                            case 'J':
                            case 'K':
                            case 'L':
                            case 'M':
                            case 'N':
                            case 'O':
                            case 'P':
                            case 'Q':
                            case 'R':
                            case 'S':
                            case 'T':
                            case 'U':
                            case 'V':
                            case 'W':
                            case 'X':
                            case 'Y':
                            case 'Z':
                            case '_':
                                i++;
                                while (i < str.Length && (IsIdentifierChar(str[i]) || IsDigit(str[i])))
                                {
                                    i++;
                                }
                                goto BreakLoop;

                            default:
                                goto BreakLoop;
                            }
BreakLoop:
                            break;
                        }
                    }

                    string tStr;
                    if (i <= str.Length)
                    {
                        tStr = str.Substring(0, i);
                    }
                    else
                    {
                        tStr = str;
                    }
                    var ed = CompletionFacilities.GenEditorData(line, i - lineStart, tStr);
                    var g  = new SpecializedDataGen();
                    try
                    {
                        CodeCompletion.GenerateCompletionData(ed, g, 'a', true);
                    }
                    catch (OperationCanceledException)
                    {
                        TimeoutsTriggered.Add(i);
                    }
                    catch (Exception e)
                    {
                        ExceptionsTriggered.Add(new Tuple <int, string>(i, e.Message + "\r\nStack Trace:\r\n" + e.StackTrace));
                    }

                    i++;
                }
            }
            catch (Exception e)
            {
                if (!Directory.Exists(Program.TesterErrorsDirectory))
                {
                    Directory.CreateDirectory(Program.TesterErrorsDirectory);
                }
                File.WriteAllText(Program.TesterErrorsDirectory + "\\" + ShortFilePath.Replace('\\', '_') + "-" + i.ToString() + ".txt", e.Message + "\r\nStack Trace:\r\n" + e.StackTrace);
            }
        }