Exemplo n.º 1
0
            public static bool ScanForConstructors(NewExpression sr, IBlockNode scope, UserDefinedType udt, List <AbstractType> _ctors, out bool explicitCtorFound)
            {
                explicitCtorFound = false;
                var ct = new CtorScan(sr, new ResolutionContext(new Misc.ParseCacheView(new RootPackage[] {}), null, scope));

                ct.DeepScanClass(udt, MemberFilter.Methods, false);

                _ctors.AddRange(ct.matches_types);

                var rawList = (udt.Definition as DClassLike)[DMethod.ConstructorIdentifierHash];

                if (rawList != null)
                {
                    foreach (var n in rawList)
                    {
                        var dm = n as DMethod;
                        if (dm == null || dm.IsStatic || dm.SpecialType != DMethod.MethodType.Constructor)
                        {
                            continue;
                        }

                        explicitCtorFound = true;
                        break;
                    }
                }

                return(ct.matches_types.Count != 0);
            }
 public CtrlSpaceCompletionProvider(ICompletionDataGenerator cdg, IBlockNode b, IStatement stmt, MemberFilter vis = MemberFilter.All)
     : base(cdg)
 {
     this.curBlock  = b;
     this.curStmt   = stmt;
     visibleMembers = vis;
 }
Exemplo n.º 3
0
        private static void HandleNewExpression_Ctor(NewExpression nex, IBlockNode curBlock, List <AbstractType> _ctors, AbstractType t)
        {
            var udt = t as TemplateIntermediateType;

            if (udt is ClassType || udt is StructType)
            {
                bool explicitCtorFound;

                if (!CtorScan.ScanForConstructors(nex, curBlock, udt, _ctors, out explicitCtorFound))
                {
                    if (explicitCtorFound)
                    {
                        // TODO: Somehow inform the user that the current class can't be instantiated
                    }
                    else
                    {
                        // Introduce default constructor
                        _ctors.Add(new MemberSymbol(new DMethod(DMethod.MethodType.Constructor)
                        {
                            Description = "Default constructor for " + udt.Name,
                            Parent      = udt.Definition
                        }, udt, nex));
                    }
                }
            }
        }
Exemplo n.º 4
0
 private ParameterInsightResolution(IEditorData ed, ResolutionContext c, ArgumentsResolutionResult r, IBlockNode cs)
 {
     Editor   = ed;
     ctxt     = c;
     res      = r;
     curScope = cs;
 }
        public static void EnumChildren(ICompletionDataGenerator cdgen,ResolutionContext ctxt, IBlockNode block, bool isVarInstance,
			MemberFilter vis = MemberFilter.Methods | MemberFilter.Types | MemberFilter.Variables | MemberFilter.Enums, bool publicImports = false)
        {
            var scan = new MemberCompletionEnumeration(ctxt, cdgen) { isVarInst = isVarInstance };

            scan.ScanBlock(block, CodeLocation.Empty, vis, publicImports);
        }
Exemplo n.º 6
0
        static void BuildTreeChildren(TreeStore Tree, TreeIter ParentTreeNode, IBlockNode ParentAstNode)
        {
            if (ParentAstNode == null)
            {
                return;
            }

            foreach (var n in ParentAstNode)
            {
                if (!DCodeCompletionSupport.CanItemBeShownGenerally(n as DNode))
                {
                    continue;
                }

                TreeIter childIter;
                if (!ParentTreeNode.Equals(TreeIter.Zero))
                {
                    childIter = Tree.AppendValues(ParentTreeNode, n);
                }
                else
                {
                    childIter = Tree.AppendValues(n);
                }

                BuildTreeChildren(Tree, childIter, n as IBlockNode);
            }
        }
Exemplo n.º 7
0
        public void Set(IBlockNode b)
        {
            scopedBlock = b;
            Caret = CodeLocation.Empty;

            ConditionalCompilation.EnumConditions(DeclarationCondititons, b, ctxt, CodeLocation.Empty);
        }
Exemplo n.º 8
0
        void CreateDeeperLevelCache(IBlockNode bn)
        {
            var dd = TypeCache[bn] = new Dictionary <string, INode>();

            // Set the parent to null to crawl through current level only. Imports/Mixins etc. will be handled though.
            var parentBackup = bn.Parent;

            bn.Parent = null;

            sharedCtxt.CurrentContext.ScopedBlock = bn;
            var vis = ItemEnumeration.EnumAllAvailableMembers(sharedCtxt, bn.EndLocation, MemberFilter.Types);

            if (vis != null)
            {
                foreach (var n in vis)
                {
                    if (!string.IsNullOrEmpty(n.Name))
                    {
                        dd[n.Name] = n;
                    }
                }
            }

            bn.Parent = parentBackup;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Used for caching available types.
        /// </summary>
        protected override void OnScopedBlockChanged(IBlockNode bn)
        {
            Dictionary <int, byte> dd = null;

            foreach (var n in ItemEnumeration.EnumScopedBlockChildren(ctxt, MemberFilter.Types | MemberFilter.Enums))
            {
                if (n.NameHash != 0)
                {
                    if (dd == null && !TypeCache.TryGetValue(bn, out dd))
                    {
                        TypeCache [bn] = dd = new Dictionary <int, byte> ();
                    }

                    byte type = 0;

                    if (n is DClassLike)
                    {
                        type = (n as DClassLike).ClassType;
                    }
                    else if (n is DEnum)
                    {
                        type = DTokens.Enum;
                    }
                    else if (n is TemplateParameter.Node)
                    {
                        type = DTokens.Not;                         // Only needed for highlighting and thus just a convention question
                    }
                    dd[n.NameHash] = type;
                }
            }
        }
Exemplo n.º 10
0
        public void Set(IBlockNode b, CodeLocation caret)
        {
            scopedBlock = b;
            Caret       = caret;

            ConditionalCompilation.EnumConditions(DeclarationCondititons, b, ctxt, caret);
        }
Exemplo n.º 11
0
 public virtual void VisitChildren(IBlockNode block)
 {
     foreach (var n in block)
     {
         n.Accept(this);
     }
 }
Exemplo n.º 12
0
 public MemberCompletionProvider(ICompletionDataGenerator cdg, ISyntaxRegion sr, IBlockNode b, IStatement stmt)
     : base(cdg)
 {
     AccessExpression = sr;
     ScopedBlock = b;
     ScopedStatement = stmt;
 }
Exemplo n.º 13
0
        public void Set(IBlockNode b)
        {
            scopedBlock = b;
            Caret       = CodeLocation.Empty;

            ConditionalCompilation.EnumConditions(DeclarationCondititons, b, ctxt, CodeLocation.Empty);
        }
Exemplo n.º 14
0
 void GenerateFoldsInternal(List <FoldingRegion> l, IBlockNode block)
 {
     if (block != null)
     {
         block.Accept(new FoldingVisitor(l));
     }
 }
Exemplo n.º 15
0
        public static ISyntaxRegion FindCurrentCaretContext(IEditorData editor, 
			ref IBlockNode currentScope, 
			out IStatement currentStatement,
			out bool isInsideNonCodeSegment)
        {
            isInsideNonCodeSegment = false;
            currentStatement = null;

            if(currentScope == null)
                currentScope = DResolver.SearchBlockAt (editor.SyntaxTree, editor.CaretLocation, out currentStatement);

            if (currentScope == null)
                return null;

            BlockStatement blockStmt;
            // Always skip lambdas as they're too quirky for accurate scope calculation // ISSUE: May be other anon symbols too?
            var dm = currentScope as DMethod;
            if (dm != null && (dm.SpecialType & DMethod.MethodType.Lambda) != 0)
                currentScope = dm.Parent as IBlockNode;

            if (currentScope is DMethod &&
                (blockStmt = (currentScope as DMethod).GetSubBlockAt (editor.CaretLocation)) != null) {
                blockStmt.UpdateBlockPartly (editor, out isInsideNonCodeSegment);
                currentScope = DResolver.SearchBlockAt (currentScope, editor.CaretLocation, out currentStatement);
            }else {
                while (currentScope is DMethod)
                    currentScope = currentScope.Parent as IBlockNode;
                if (currentScope == null)
                    return null;

                (currentScope as DBlockNode).UpdateBlockPartly (editor, out isInsideNonCodeSegment);
                currentScope = DResolver.SearchBlockAt (currentScope, editor.CaretLocation, out currentStatement);
            }
            return currentScope;
        }
Exemplo n.º 16
0
        public void CreatePseudoAliases(IBlockNode Parent)
        {
            PseudoAliases.Clear();

            foreach (var imp in Imports)
            {
                if (imp.ModuleAlias != null)
                {
                    PseudoAliases.Add(new ModuleAliasNode(this, imp, Parent));
                }
            }

            if (ImportBindList != null)
            {
                /*
                 * import cv=std.conv : Convert = to;
                 *
                 * cv can be still used as an alias for std.conv,
                 * whereas Convert is a direct alias for std.conv.to
                 */
                if (ImportBindList.Module.ModuleAlias != null)
                {
                    PseudoAliases.Add(new ModuleAliasNode(this, ImportBindList.Module, Parent));
                }

                foreach (var bind in ImportBindList.SelectedSymbols)
                {
                    PseudoAliases.Add(new ImportSymbolAlias(this, bind, Parent));
                }
            }
        }
Exemplo n.º 17
0
        public ContextFrame(ResolutionContext ctxt, IBlockNode b, IStatement stmt = null)
        {
            this.ctxt = ctxt;
            declarationCondititons = new ConditionalCompilation.ConditionSet(ctxt.CompilationEnvironment);

            Set(b,stmt);
        }
Exemplo n.º 18
0
        void SearchResultsIn(IBlockNode block, string pattern, List <INode> results, int maxResults)
        {
            // Don't search in modules themselves!

            if (block.Children.Count == 0 || results.Count > maxResults)
            {
                return;
            }

            foreach (var n in block.Children)
            {
                if (!results.Contains(n) && n.Name.Contains(pattern))
                {
                    if (!results.Contains(n))
                    {
                        results.Add(n);
                    }
                }

                if (n is IBlockNode)
                {
                    SearchResultsIn(n as IBlockNode, pattern, results, maxResults);
                }

                if (results.Count > maxResults)
                {
                    return;
                }
            }
        }
Exemplo n.º 19
0
        public static List <FoldingRange> GenerateFoldsInternal(IBlockNode block)
        {
            var l = new List <FoldingRange>();

            block?.Accept(new FoldingVisitor(l));
            return(l);
        }
 public CtrlSpaceCompletionProvider(ICompletionDataGenerator cdg, IBlockNode b, IStatement stmt, MemberFilter vis = MemberFilter.All)
     : base(cdg)
 {
     this.curBlock = b;
     this.curStmt = stmt;
     visibleMembers = vis;
 }
Exemplo n.º 21
0
		public void Set(IBlockNode b, CodeLocation caret)
		{
			scopedBlock = b;
			Caret = caret;
			
			ConditionalCompilation.EnumConditions(DeclarationCondititons, b, ctxt, caret); 
		}
Exemplo n.º 22
0
 public CtrlSpaceCompletionProvider(ICompletionDataGenerator cdg, IBlockNode b, MemberFilter vis = MemberFilter.All, params byte[] specialKeywords)
     : base(cdg)
 {
     this.curBlock        = b;
     visibleMembers       = vis;
     this.specialKeywords = specialKeywords;
 }
Exemplo n.º 23
0
        public ContextFrame(ResolutionContext ctxt, IBlockNode b, IStatement stmt = null)
        {
            this.ctxt = ctxt;
            declarationCondititons = new ConditionalCompilation.ConditionSet(ctxt.CompilationEnvironment);

            Set(b, stmt);
        }
Exemplo n.º 24
0
 public static void EnumConditions(ConditionSet cs, IBlockNode block, ResolutionContext ctxt, CodeLocation caret)
 {
     if (block != null && block.NodeRoot != null)
     {
         block.NodeRoot.Accept(new ConditionVisitor(cs, ctxt, caret));
     }
     return;
 }
 /// <summary>Gets the score of the best (first) node.</summary>
 public int GetScore(IBlockNode node)
 {
     if (Empty())
     {
         return(Scores.Loses(node.Depth));
     }
     return(this[0].Score);
 }
Exemplo n.º 26
0
            public static void RemoveDoubles(IBlockNode originalAst, IBlockNode blockToClean)
            {
                var rem = new DoubleDeclarationSilencer();

                originalAst.Accept(rem);
                rem.secondRun = true;
                blockToClean.Accept(rem);
            }
Exemplo n.º 27
0
        public void ApplyFrom(ResolverContext other)
        {
            if (other == null)
                return;

            ScopedBlock = other.ScopedBlock;
            ScopedStatement = other.ScopedStatement;
        }
Exemplo n.º 28
0
        void GenerateFoldsInternal(List <FoldingRegion> l, IBlockNode block)
        {
            if (block == null)
            {
                return;
            }

            if (!(block is DModule) && !block.Location.IsEmpty && block.EndLocation > block.Location)
            {
                if (block is DMethod)
                {
                    var dm = block as DMethod;

                    if (dm.In != null)
                    {
                        GenerateFoldsInternal(l, dm.In);
                    }
                    if (dm.Out != null)
                    {
                        GenerateFoldsInternal(l, dm.Out);
                    }
                    if (dm.Body != null)
                    {
                        GenerateFoldsInternal(l, dm.Body);
                    }
                }
                else
                {
                    l.Add(new FoldingRegion(GetBlockBodyRegion(block), FoldType.Type));
                }
            }

            if (block.Count > 0)
            {
                foreach (var n in block)
                {
                    GenerateFoldsInternal(l, n as IBlockNode);
                }
            }

            if (block is DBlockNode)
            {
                var dbn = block as DBlockNode;
                if (dbn.MetaBlocks != null)
                {
                    for (int i = dbn.MetaBlocks.Count - 1; i >= 0; i--)
                    {
                        var mdb = dbn.MetaBlocks[i] as IMetaDeclarationBlock;
                        if (mdb != null)
                        {
                            l.Add(new FoldingRegion(
                                      new DomRegion(mdb.BlockStartLocation.Line, mdb.BlockStartLocation.Column, mdb.EndLocation.Line, mdb.EndLocation.Column),
                                      FoldType.Undefined));
                        }
                    }
                }
            }
        }
Exemplo n.º 29
0
        public ContextFrame(ResolutionContext ctxt, IBlockNode b, CodeLocation caret)
        {
            this.ctxt = ctxt;
            DeclarationCondititons = new ConditionalCompilation.ConditionSet(ctxt.CompilationEnvironment);

            ctxt.Push(this);

            Set(b, caret);
        }
Exemplo n.º 30
0
        public static ISyntaxRegion FindCurrentCaretContext(IEditorData editor,
                                                            ref IBlockNode currentScope,
                                                            out bool isInsideNonCodeSegment)
        {
            isInsideNonCodeSegment = false;

            if (currentScope == null)
            {
                currentScope = DResolver.SearchBlockAt(editor.SyntaxTree, editor.CaretLocation);
            }

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

            // class asd : |
            if (currentScope is IBlockNode && (currentScope as IBlockNode).BlockStartLocation > editor.CaretLocation)
            {
                currentScope = currentScope.Parent as IBlockNode;
            }

            BlockStatement blockStmt;
            // Always skip lambdas as they're too quirky for accurate scope calculation // ISSUE: May be other anon symbols too?
            var dm = currentScope as DMethod;

            if (dm != null && (dm.SpecialType & DMethod.MethodType.Lambda) != 0)
            {
                currentScope = dm.Parent as IBlockNode;
            }

            if (currentScope is DMethod &&
                (blockStmt = (currentScope as DMethod).GetSubBlockAt(editor.CaretLocation)) != null)
            {
                var tempBlock = blockStmt.UpdateBlockPartly(editor, out isInsideNonCodeSegment);
                if (tempBlock == null)
                {
                    return(null);
                }
                currentScope = DResolver.SearchBlockAt(tempBlock, editor.CaretLocation);
            }
            else
            {
                while (currentScope is DMethod)
                {
                    currentScope = currentScope.Parent as IBlockNode;
                }
                if (currentScope == null)
                {
                    return(null);
                }

                var tempBlock = (currentScope as DBlockNode).UpdateBlockPartly(editor, out isInsideNonCodeSegment);
                currentScope = DResolver.SearchBlockAt(tempBlock, editor.CaretLocation);
            }
            return(currentScope);
        }
Exemplo n.º 31
0
            public override void VisitChildren(IBlockNode block)
            {
                var ch = DResolver.SearchRegionAt <INode>(block.Children, caret);

                if (ch != null && ch != block)
                {
                    ch.Accept(this);
                }
            }
Exemplo n.º 32
0
        public void ApplyFrom(ResolverContext other)
        {
            if (other == null)
            {
                return;
            }

            ScopedBlock     = other.ScopedBlock;
            ScopedStatement = other.ScopedStatement;
        }
Exemplo n.º 33
0
        public ModuleAliasNode(ImportStatement impStmt, ImportStatement.Import imp, IBlockNode parentNode)
            : base(impStmt, parentNode)
        {
            this.Import = imp;

            Name     = imp.ModuleAlias.Id;
            Location = NameLocation = imp.ModuleIdentifier.Location;

            Type = imp.ModuleIdentifier;
        }
Exemplo n.º 34
0
		public static BracketSearchResult SearchBrackets(TextDocument doc, IEditorData ed, IBlockNode curBlock, IStatement stmt)
		{
			while (stmt != null)
			{
				if (stmt is IExpressionContainingStatement)
				{
					var ecs = (IExpressionContainingStatement)stmt;
					foreach (var x in ecs.SubExpressions)
					{
						SurroundingParenthesesExpression spe = null;
						var xx = x;
						while (xx is ContainerExpression)
						{
							if (xx is SurroundingParenthesesExpression)
								spe = (SurroundingParenthesesExpression)xx;

							var subX = ((ContainerExpression)xx).SubExpressions;
							if (subX != null && subX.Length != 0)
							{
								xx = null;
								foreach (var sx in subX)
									if (ed.CaretLocation > sx.Location && ed.CaretLocation < sx.EndLocation)
									{
										xx = sx as ContainerExpression;
										break;
									}
							}
						}

						if (spe != null)
							return new BracketSearchResult(
								doc.GetOffset(spe.Location.Line, spe.Location.Column), 1,
								doc.GetOffset(spe.EndLocation.Line, spe.EndLocation.Column) - 1, 1);
					}
				}

				if (stmt is BlockStatement)
					return new BracketSearchResult(
						doc.GetOffset(stmt.Location.Line, stmt.Location.Column), 1,
						doc.GetOffset(stmt.EndLocation.Line, stmt.EndLocation.Column) - 1, 1);
				stmt = stmt.Parent;
			}

			if (curBlock != null && ed.CaretLocation < curBlock.BlockStartLocation)
				curBlock = curBlock.Parent as IBlockNode;

			if (curBlock == null || curBlock is DModule)
				return null;

			//TODO: Meta blocks, everything that could contain parentheses
			return new BracketSearchResult(
				doc.GetOffset(curBlock.BlockStartLocation.Line, curBlock.BlockStartLocation.Column), 1,
				doc.GetOffset(curBlock.EndLocation.Line, curBlock.EndLocation.Column) - 1, 1);
		}
Exemplo n.º 35
0
        public override void VisitChildren(IBlockNode block)
        {
            var b = scopedBlock;
            var s = scopedStatement;

            scopedStatement = null;
            scopedBlock     = block;
            base.VisitChildren(block);
            scopedBlock     = b;
            scopedStatement = s;
        }
Exemplo n.º 36
0
        public ResolverContext PushNewScope(IBlockNode scope)
        {
            var ctxtOverride = new ResolverContext();

            ctxtOverride.ScopedBlock     = scope;
            ctxtOverride.ScopedStatement = null;

            stack.Push(ctxtOverride);

            return(ctxtOverride);
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            Utils.FormatLineForTextControl(solution, textControl);

            IElement   element         = Utils.GetElementAtCaret(solution, textControl);
            IBlockNode containingBlock = element.GetContainingElement <IBlockNode>(true);

            if (containingBlock != null)
            {
                new SpacingRules().SingleLineCommentsMustBeginWithSingleSpace(element.ToTreeNode());
            }
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            Utils.FormatLineForTextControl(solution, textControl);

            IElement   element         = Utils.GetElementAtCaret(solution, textControl);
            IBlockNode containingBlock = element.GetContainingElement <IBlockNode>(true);

            if (containingBlock != null)
            {
                new SpacingRules().CodeMustNotContainMultipleWhitespaceInARow(element.ToTreeNode());
            }
        }
Exemplo n.º 39
0
 public override IEnumerable <INode> PrefilterSubnodes(IBlockNode bn)
 {
     if (bn is DModule)
     {
         if (nameFilterHash == 0)
         {
             return(bn.Children);
         }
         return(bn [nameFilterHash]);
     }
     return(null);
 }
Exemplo n.º 40
0
        public static void EnumAllAvailableMembers(ICompletionDataGenerator cdgen, IBlockNode ScopedBlock
			, IStatement ScopedStatement,
			CodeLocation Caret,
		    ParseCacheView CodeCache,
			MemberFilter VisibleMembers,
			ConditionalCompilationFlags compilationEnvironment = null)
        {
            var ctxt = ResolutionContext.Create(CodeCache, compilationEnvironment, ScopedBlock, ScopedStatement);

            var en = new MemberCompletionEnumeration(ctxt, cdgen) {isVarInst = true};

            en.IterateThroughScopeLayers(Caret, VisibleMembers);
        }
Exemplo n.º 41
0
        public static IEnumerable<INode> EnumAllAvailableMembers(IBlockNode ScopedBlock
			, IStatement ScopedStatement,
			CodeLocation Caret,
			ParseCacheList CodeCache,
			MemberFilter VisibleMembers)
        {
            return EnumAllAvailableMembers(new ResolverContextStack(CodeCache,new ResolverContext
            {
                ScopedBlock = ScopedBlock,
                ScopedStatement = ScopedStatement
            }),
            Caret,
            VisibleMembers);
        }
Exemplo n.º 42
0
        public void BeginUpdate()
        {
            if (hasBegun)
                return;

            hasBegun = true;
            currentCol = Document.Editor.Caret.Column;
            currentLine = Document.Editor.Caret.Line;
            var caret = new CodeLocation(currentCol, currentLine);
            currentBlock = DResolver.SearchBlockAt(Ast, caret, out currentStmt);

            isBeforeBlockStart = currentBlock != null && caret <= currentBlock.BlockStartLocation;
            isAtStmtStart = currentStmt != null && caret == currentStmt.Location;
        }
Exemplo n.º 43
0
        public static void EnumConditions(ConditionSet cs,IStatement stmt, IBlockNode block, ResolutionContext ctxt, CodeLocation caret)
        {
            var l = new MutableConditionFlagSet();
            cs.LocalFlags = l;

            // If the current scope is a dedicated block.. (so NOT in a method but probably in an initializer or other static statement)
            if(block is DBlockNode)
            {
                // If so, get all (scoping) declaration conditions in the current block
                // and add them to the condition list
                var mblocks = ((DBlockNode)block).GetMetaBlockStack(caret, false, true);

                if(mblocks!=null && mblocks.Length!=0)
                    foreach(var mb in mblocks)
                    {
                        var amd = mb as AttributeMetaDeclaration;
                        if(amd!=null && amd.AttributeOrCondition!=null && amd.AttributeOrCondition.Length!=0)
                            foreach(var attr in amd.AttributeOrCondition)
                                if(attr is DeclarationCondition)
                                    l.Add((DeclarationCondition)attr);
                    }
            }

            // Scan up the current statement when e.g. inside a method body
            while (stmt != null)
            {
                if (stmt is StatementCondition)
                    l.Add(((StatementCondition)stmt).Condition);
                stmt = stmt.Parent;
            }

            // Go up the block hierarchy and add all conditions that belong to the respective nodes
            while (block != null)
            {
                var dn = block as DNode;
                if (dn!=null)
                {
                    if(dn is DBlockNode)
                        GetDoneVersionDebugSpecs(cs, l, dn as DBlockNode, ctxt);
                    if(dn.Attributes!=null)
                        foreach (var attr in dn.Attributes)
                            if (attr is DeclarationCondition)
                                l.Add(((DeclarationCondition)attr));
                }

                block = block.Parent as IBlockNode;
            }
        }
Exemplo n.º 44
0
        public void Set(IBlockNode b, IStatement stmt = null)
        {
            scopedBlock = b;
            scopedStmt = stmt;

            var c = CodeLocation.Empty; //TODO: Take the caret position if we're in the currently edited module and the scoped block is the module root(?)
            if(stmt == null)
            {
                if(b!=null)
                    c = b.BlockStartLocation;
            }
            else
                c = stmt.Location;

            ConditionalCompilation.EnumConditions(declarationCondititons, stmt, b, ctxt, c);
        }
Exemplo n.º 45
0
		void CreateDeeperLevelCache(IBlockNode bn)
		{
			var dd = TypeCache[bn] = new Dictionary<int,INode>();

			// Set the parent to null to crawl through current level only. Imports/Mixins etc. will be handled though.
			var parentBackup = bn.Parent;
			bn.Parent = null;

			sharedCtxt.CurrentContext.Set(bn);
			foreach (var n in ItemEnumeration.EnumScopedBlockChildren(sharedCtxt, MemberFilter.Types))
			{
				if (n.NameHash != 0)
					dd[n.NameHash] = n;
			}

			bn.Parent = parentBackup;
		}
		public override void VisitChildren (IBlockNode block)
		{
			if (!halt)
				shownKeywords.Push(BlockMemberFilter);

			var en = block.GetEnumerator ();
			while (!halt && en.MoveNext ()) {
				if (en.Current.Location > ed.CaretLocation) {
					halt = true;
					return;
				}
				en.Current.Accept (this);
			}

			if (!halt)
				shownKeywords.Pop ();
		}
Exemplo n.º 47
0
		void SearchResultsIn(IBlockNode block, string pattern, List<INode> results, int maxResults)
		{
			// Don't search in modules themselves!

			if (block.Children.Count == 0 || results.Count > maxResults)
				return;

			foreach (var n in block.Children) {
				if(!results.Contains(n) && n.Name.Contains(pattern))
					if(!results.Contains(n))
						results.Add(n);
				
				if(n is IBlockNode)
					SearchResultsIn(n as IBlockNode, pattern, results, maxResults);

				if (results.Count > maxResults)
					return;
			}
		}
Exemplo n.º 48
0
		public void FinishUpdate()
		{
			if (!hasBegun)
				return;

			hasBegun = false;

			int lineDiff = Editor.Caret.Line - currentLine;
			int colDiff = Editor.Caret.Column - currentCol;

			while (currentBlock != null)
			{
				if (isBeforeBlockStart)
				{
					currentBlock.BlockStartLocation = new CodeLocation(
						currentBlock.BlockStartLocation.Column + (currentBlock.BlockStartLocation.Line == Editor.Caret.Line ? colDiff : 0),
						currentBlock.BlockStartLocation.Line + lineDiff);
					isBeforeBlockStart = false;
				}

				currentBlock.EndLocation = new CodeLocation(
						currentBlock.EndLocation.Column + (currentBlock.EndLocation.Line == Editor.Caret.Line ? colDiff : 0),
						currentBlock.EndLocation.Line + lineDiff);
				currentBlock = currentBlock.Parent as IBlockNode;
			}

			while (currentStmt != null)
			{
				if (isAtStmtStart)
				{
					isAtStmtStart = currentStmt.Parent != null && currentStmt.Location == currentStmt.Parent.Location;
					currentStmt.Location = new CodeLocation(
						currentStmt.Location.Column + colDiff,
						currentStmt.Location.Line + lineDiff);
				}

				currentStmt.EndLocation = new CodeLocation(
						currentStmt.EndLocation.Column + (currentStmt.EndLocation.Line == Editor.Caret.Line ? colDiff : 0),
						currentStmt.EndLocation.Line + lineDiff);
				currentStmt = currentStmt.Parent;
			}
		}
        static void HandleNewExpression(NewExpression nex, 
			ArgumentsResolutionResult res, 
			IEditorData Editor, 
			ResolutionContext ctxt,
			IBlockNode curBlock,
			IEnumerable<AbstractType> resultBases = null)
        {
            res.MethodIdentifier = nex;
            CalculateCurrentArgument(nex, res, Editor.CaretLocation, ctxt);

            var type = TypeDeclarationResolver.ResolveSingle(nex.Type, ctxt);

            var _ctors = new List<AbstractType>();

            if (type is AmbiguousType)
                foreach (var t in (type as AmbiguousType).Overloads)
                    HandleNewExpression_Ctor(nex, curBlock, _ctors, t);
            else
                HandleNewExpression_Ctor(nex, curBlock, _ctors, type);

            res.ResolvedTypesOrMethods = _ctors.ToArray();
        }
Exemplo n.º 50
0
        /// <summary>
        /// Used for caching available types.
        /// </summary>
        protected override void OnScopedBlockChanged(IBlockNode bn)
        {
            Dictionary<int,byte> dd = null;
            foreach (var n in ItemEnumeration.EnumScopedBlockChildren(ctxt, MemberFilter.Types | MemberFilter.Enums))
            {
                if (n.NameHash != 0) {
                    if (dd == null && !TypeCache.TryGetValue (bn, out dd))
                        TypeCache [bn] = dd = new Dictionary<int,byte> ();

                    byte type = 0;

                    if (n is DClassLike)
                        type = (n as DClassLike).ClassType;
                    else if (n is DEnum)
                        type = DTokens.Enum;
                    else if (n is TemplateParameter.Node)
                        type = DTokens.Not; // Only needed for highlighting and thus just a convention question

                    dd[n.NameHash] = type;
                }
            }
        }
        static void HandleNewExpression(NewExpression nex, 
			ArgumentsResolutionResult res, 
			IEditorData Editor, 
			ResolverContextStack ctxt,
			IBlockNode curBlock)
        {
            res.MethodIdentifier = nex;
            CalculateCurrentArgument(nex, res, Editor.CaretLocation, ctxt);

            var type = TypeDeclarationResolver.ResolveSingle(nex.Type, ctxt) as ClassType;

            //TODO: Inform the user that only classes can be instantiated
            if (type != null)
            {
                var constructors = new List<DMethod>();
                bool explicitCtorFound = false;

                foreach (var member in type.Definition)
                {
                    var dm = member as DMethod;

                    if (dm != null && dm.SpecialType == DMethod.MethodType.Constructor)
                    {
                        explicitCtorFound = true;
                        if (!dm.IsPublic)
                        {
                            var curNode = curBlock;
                            bool pass = false;
                            do
                            {
                                if (curNode == type.Definition)
                                {
                                    pass = true;
                                    break;
                                }
                            }
                            while ((curNode = curNode.Parent as IBlockNode) != curNode);

                            if (!pass)
                                continue;
                        }

                        constructors.Add(dm);
                    }
                }

                if (constructors.Count == 0)
                {
                    if (explicitCtorFound)
                    {
                        // TODO: Somehow inform the user that the current class can't be instantiated
                    }
                    else
                    {
                        // Introduce default constructor
                        constructors.Add(new DMethod(DMethod.MethodType.Constructor)
                        {
                            Description = "Default constructor for " + type.Name,
                            Parent = type.Definition
                        });
                    }
                }

                // Wrapp all ctor members in MemberSymbols
                var _ctors = new List<AbstractType>();
                foreach (var ctor in constructors)
                    _ctors.Add(new MemberSymbol(ctor, type, nex.Type));
                res.ResolvedTypesOrMethods = _ctors.ToArray();

                //TODO: Probably pre-select the current ctor by handling previously typed arguments etc.
            }
        }
Exemplo n.º 52
0
 public static void RemoveDoubles(IBlockNode originalAst, IBlockNode blockToClean)
 {
     var rem = new DoubleDeclarationSilencer();
     originalAst.Accept(rem);
     rem.secondRun = true;
     blockToClean.Accept(rem);
 }
		public virtual void VisitChildren(IBlockNode block)
		{
			foreach (var n in block)
				n.Accept(this);
		}
        private static void HandleNewExpression_Ctor(NewExpression nex, IBlockNode curBlock, List<AbstractType> _ctors, AbstractType t)
        {
            var udt = t as TemplateIntermediateType;
            if (udt is ClassType || udt is StructType)
            {
                bool explicitCtorFound = false;
                var constructors = new List<DMethod>();

                //TODO: Mixed-in ctors? --> Convert to AbstractVisitor/use NameScan
                foreach (var member in udt.Definition)
                {
                    var dm = member as DMethod;

                    if (dm != null && dm.SpecialType == DMethod.MethodType.Constructor)
                    {
                        explicitCtorFound = true;
                        if (!dm.IsPublic)
                        {
                            var curNode = curBlock;
                            bool pass = false;
                            do
                            {
                                if (curNode == udt.Definition)
                                {
                                    pass = true;
                                    break;
                                }
                            }
                            while ((curNode = curNode.Parent as IBlockNode) != curNode);

                            if (!pass)
                                continue;
                        }

                        constructors.Add(dm);
                    }
                }

                if (constructors.Count == 0)
                {
                    if (explicitCtorFound)
                    {
                        // TODO: Somehow inform the user that the current class can't be instantiated
                    }
                    else
                    {
                        // Introduce default constructor
                        constructors.Add(new DMethod(DMethod.MethodType.Constructor)
                        {
                            Description = "Default constructor for " + udt.Name,
                            Parent = udt.Definition
                        });
                    }
                }

                // Wrapp all ctor members in MemberSymbols
                foreach (var ctor in constructors)
                    _ctors.Add(new MemberSymbol(ctor, t, nex.Type));
            }
        }
		public static ISyntaxRegion FindCurrentCaretContext(IEditorData editor, 
			out ParserTrackerVariables trackerVariables, 
			ref IBlockNode currentScope, 
			out IStatement currentStatement)
		{
			if(currentScope == null)
				currentScope = DResolver.SearchBlockAt (editor.SyntaxTree, editor.CaretLocation, out currentStatement);

			if (currentScope == null) {
				trackerVariables = null;
				currentStatement = null;
				return null;
			}

			bool ParseDecl = false;

			int blockStart = 0;
			var blockStartLocation = currentScope != null ? currentScope.BlockStartLocation : editor.CaretLocation;

			if (currentScope is DMethod)
			{
				var block = (currentScope as DMethod).GetSubBlockAt(editor.CaretLocation);

				if (block != null)
					blockStart = DocumentHelper.GetOffsetByRelativeLocation (editor.ModuleCode, editor.CaretLocation, editor.CaretOffset, blockStartLocation = block.Location);
				else {
					currentScope = currentScope.Parent as IBlockNode;
					return FindCurrentCaretContext (editor, out trackerVariables, ref currentScope, out currentStatement);
				}
			}
			else if (currentScope != null)
			{
				if (currentScope.BlockStartLocation.IsEmpty || (editor.CaretLocation < currentScope.BlockStartLocation && editor.CaretLocation > currentScope.Location))
				{
					ParseDecl = true;
					blockStart = DocumentHelper.GetOffsetByRelativeLocation(editor.ModuleCode, editor.CaretLocation, editor.CaretOffset, blockStartLocation = currentScope.Location);
				}
				else
					blockStart = DocumentHelper.GetOffsetByRelativeLocation(editor.ModuleCode, editor.CaretLocation, editor.CaretOffset, currentScope.BlockStartLocation);
			}

			if (blockStart >= 0 && editor.CaretOffset - blockStart > 0)
				using (var sr = new Misc.StringView(editor.ModuleCode, blockStart, editor.CaretOffset - blockStart))
				{
					var psr = DParser.Create(sr);

					/*					 Deadly important! For correct resolution behaviour, 
					 * it is required to set the parser virtually to the blockStart position, 
					 * so that everything using the returned object is always related to 
					 * the original code file, not our code extraction!
					 */
					psr.Lexer.SetInitialLocation(blockStartLocation);

					ISyntaxRegion ret = null;

					if (currentScope == null)
						ret = psr.Parse();
					else if (currentScope is DMethod)
					{
						psr.Step();
						var dm = currentScope as DMethod;
						dm.Clear();

						if ((dm.SpecialType & DMethod.MethodType.Lambda) != 0 &&
							psr.Lexer.LookAhead.Kind != DTokens.OpenCurlyBrace) {
							psr.LambdaSingleStatementBody (dm);
							ret = dm.Body;
						} else {
							var methodRegion = DTokens.Body;

							if (dm.In != null && blockStartLocation == dm.In.Location)
								methodRegion = DTokens.In;

							if (dm.Out != null && blockStartLocation == dm.Out.Location)
								methodRegion = DTokens.Out;

							var newBlock = psr.BlockStatement (currentScope);
							ret = newBlock;

							switch (methodRegion) {
								case DTokens.Body:
									newBlock.EndLocation = dm.Body.EndLocation;
									dm.Body = newBlock;
									break;
								case DTokens.In:
									newBlock.EndLocation = dm.In.EndLocation;
									dm.In = newBlock;
									break;
								case DTokens.Out:
									newBlock.EndLocation = dm.Out.EndLocation;
									dm.Out = newBlock;
									break;
							}
						}
					}
					else if (currentScope is DModule)
						ret = psr.Root();
					else
					{
						psr.Step();
						if (ParseDecl)
						{
							var ret2 = psr.Declaration(currentScope);

							if (ret2 != null && ret2.Length > 0)
								ret = ret2[0];
						}
						else if (currentScope is DClassLike)
						{
							var t = new DClassLike((currentScope as DClassLike).ClassType);
							t.AssignFrom(currentScope);
							t.Clear();
							psr.ClassBody(t);
							ret = t;
						}
						else if (currentScope is DEnum)
						{
							var t = new DEnum();
							t.AssignFrom(currentScope);
							t.Clear();
							psr.EnumBody(t);
							ret = t;
						}
					}

					currentScope = DResolver.SearchBlockAt (currentScope, 
						psr.Lexer.CurrentToken != null ? psr.Lexer.CurrentToken.EndLocation : editor.CaretLocation, 
						out currentStatement);
					trackerVariables = psr.TrackerVariables;
					return ret;
				}

			trackerVariables = null;
			currentStatement = null;
			return null;
		}
		private ParameterInsightResolution(IEditorData ed, ResolutionContext c, ArgumentsResolutionResult r, IBlockNode cs) {
			Editor = ed;
			ctxt = c;
			res = r;
			curScope = cs;
		}
        static void HandleTemplateInstance(TemplateInstanceExpression tix,
			ArgumentsResolutionResult res,
			IEditorData Editor,
			ResolutionContext ctxt,
			IBlockNode curBlock,
			IEnumerable<AbstractType> resultBases = null)
        {
            res.IsTemplateInstanceArguments = true;

            res.MethodIdentifier = tix;
            res.ResolvedTypesOrMethods = ExpressionTypeEvaluation.GetOverloads(tix, ctxt, resultBases, false);

            if (tix.Arguments != null)
                res.CurrentlyTypedArgumentIndex = tix.Arguments.Length;
            else
                res.CurrentlyTypedArgumentIndex = 0;
        }
 protected virtual void OnScopedBlockChanged(IBlockNode bn)
 {
 }
		private bool GetVisibleMemberFilter(IEditorData Editor, char enteredChar, ref MemberFilter visibleMembers, ref IStatement curStmt)
		{
			if (trackVars == null)
			{
				// --> Happens if no actual declaration syntax given --> Show types/keywords anyway
				visibleMembers = MemberFilter.Types | MemberFilter.Keywords | MemberFilter.TypeParameters;
			}
			else
			{
				var n = trackVars.LastParsedObject as INode;
				var dv = n as DVariable;
				if (trackVars.ExpectingNodeName) {
					if (dv != null && dv.IsAlias && dv.Type == null) {
						// Show completion because no aliased type has been entered yet
					} else if (n != null && n.NameHash==0 && enteredChar != '\0')
						return false;
				}

				else if (trackVars.LastParsedObject is TokenExpression &&
					DTokens.BasicTypes[(trackVars.LastParsedObject as TokenExpression).Token] &&
					DTokens.IsIdentifierChar(enteredChar))
					return false;

				if (trackVars.LastParsedObject is Modifier)
				{
					var attr = trackVars.LastParsedObject as Modifier;

					if (attr.IsStorageClass && attr.Token != DTokens.Abstract)
						return false;
				}

				else if (trackVars.IsParsingBaseClassList)
				{
					var dc = parsedBlock as DClassLike;
					if (dc != null && dc.ClassType == DTokens.Interface)
						visibleMembers = MemberFilter.Interfaces | MemberFilter.Templates;
					else
						visibleMembers = MemberFilter.Classes | MemberFilter.Interfaces | MemberFilter.Templates;
					return true;
				}
				
				if (trackVars.IsParsingAssignExpression)
				{
					visibleMembers = MemberFilter.All;
					return true;
				}

				if ((trackVars.LastParsedObject is NewExpression && trackVars.IsParsingInitializer) ||
					trackVars.LastParsedObject is TemplateInstanceExpression && ((TemplateInstanceExpression)trackVars.LastParsedObject).Arguments == null)
					visibleMembers = MemberFilter.Types;
				else if (enteredChar == ' ')
					return false;
				// In class bodies, do not show variables
				else if (!(parsedBlock is BlockStatement || trackVars.IsParsingInitializer))
				{
					bool showVariables = false;
					var dbn = parsedBlock as DBlockNode;
					if (dbn != null && dbn.StaticStatements != null && dbn.StaticStatements.Count > 0)
					{
						var ss = dbn.StaticStatements[dbn.StaticStatements.Count - 1];
						if (Editor.CaretLocation > ss.Location && Editor.CaretLocation <= ss.EndLocation)
						{
							showVariables = true;
						}
					}

					if (!showVariables)
						visibleMembers = MemberFilter.All ^ MemberFilter.Variables;
				}

				// Hide completion if having typed a '0.' literal
				else if (trackVars.LastParsedObject is IdentifierExpression &&
					   (trackVars.LastParsedObject as IdentifierExpression).Format == LiteralFormat.Scalar)
					return false;

				/*
				 * Handle module-scoped things:
				 * When typing a dot without anything following, trigger completion and show types, methods and vars that are located in the module & import scope
				 */
				else if (trackVars.LastParsedObject is TokenExpression &&
					((TokenExpression)trackVars.LastParsedObject).Token == DTokens.Dot)
				{
					visibleMembers = MemberFilter.Methods | MemberFilter.Types | MemberFilter.Variables | MemberFilter.TypeParameters;
					curBlock = Editor.SyntaxTree;
					curStmt = null;
				}

				// In a method, parse from the method's start until the actual caret position to get an updated insight
				if (visibleMembers.HasFlag(MemberFilter.Variables) &&
					curBlock is DMethod &&
					parsedBlock is BlockStatement)
				{}
				else
					curStmt = null;
			}
			return true;
		}
Exemplo n.º 60
0
 protected virtual void OnScopeChanged(IBlockNode scopedBlock)
 {
 }