Ejemplo n.º 1
0
        static ISyntaxRegion GetLastBlockAstChild(DBlockNode n)
        {
            ISyntaxRegion lastChild = null;
            ISyntaxRegion t         = null;

            if (n.Count != 0)
            {
                lastChild = n.Children[n.Count - 1];
            }

            if (n.MetaBlocks.Count != 0)
            {
                t = n.MetaBlocks[n.MetaBlocks.Count - 1];

                if (lastChild == null || t.EndLocation > lastChild.EndLocation)
                {
                    lastChild = t;
                }
            }

            if (n.StaticStatements.Count != 0)
            {
                t = n.StaticStatements[n.StaticStatements.Count - 1];

                if (lastChild == null || t.EndLocation > lastChild.EndLocation)
                {
                    lastChild = t;
                }
            }

            return(lastChild);
        }
Ejemplo n.º 2
0
        /*
         * public imports only affect the directly superior module:
         *
         * module A:
         * import B;
         *
         * foo(); // Will fail, because foo wasn't found
         *
         * ---------------------------
         * module B:
         * import C;
         *
         * ---------------------------
         * module C:
         * public import D;
         *
         * ---------------------------
         * module D:
         * void foo() {}
         *
         * ---------------------------
         * Whereas
         * module B:
         * public import C;
         *
         * -- will compile because we have a closed import hierarchy in which all imports are public.
         *
         */

        /// <summary>
        /// Handle the node's static statements (but not the node itself)
        /// </summary>
        bool HandleDBlockNode(DBlockNode dbn, MemberFilter VisibleMembers, bool takePublicImportsOnly = false)
        {
            if (dbn != null && dbn.StaticStatements != null)
            {
                foreach (var stmt in dbn.StaticStatements)
                {
                    var dstmt = stmt as IDeclarationContainingStatement;
                    if (dstmt != null)
                    {
                        if (takePublicImportsOnly &&
                            dstmt is ImportStatement &&
                            !DAttribute.ContainsAttribute(dstmt.Attributes, DTokens.Public))
                        {
                            continue;
                        }

                        /*
                         * Mainly used for selective imports/import module aliases
                         */
                        if (dstmt.Declarations != null)
                        {
                            foreach (var d in dstmt.Declarations)
                            {
                                if (HandleItem(d))                                 //TODO: Handle visibility?
                                {
                                    return(true);
                                }
                            }
                        }

                        if (dstmt is ImportStatement)
                        {
                            var impStmt = (ImportStatement)dstmt;

                            foreach (var imp in impStmt.Imports)
                            {
                                if (string.IsNullOrEmpty(imp.ModuleAlias))
                                {
                                    if (HandleNonAliasedImport(imp, VisibleMembers))
                                    {
                                        return(true);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Every module imports 'object' implicitly
            if (!takePublicImportsOnly)
            {
                if (HandleNonAliasedImport(_objectImport, VisibleMembers))
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 3
0
        public override void VisitBlock(DBlockNode block)
        {
            // First do meta block evaluation due to conditional compilation checks
            var en = block.StaticStatements.GetEnumerator();
            var metaBlockEnumGotElements = en.MoveNext();

            using (PushConditionEnumBlock(block)) {
                if (block.MetaBlocks.Count != 0)
                {
                    foreach (var mb in block.MetaBlocks)
                    {
                        if (metaBlockEnumGotElements)
                        {
                            metaBlockEnumGotElements = ContinueEnumStaticStatements(en, mb.Location);
                        }
                        mb.Accept(this);
                    }
                }

                if (metaBlockEnumGotElements)
                {
                    ContinueEnumStaticStatements(en, block.EndLocation);
                }

                byte type;
                if (DoPrimaryIdCheck(block.NameHash, out type))
                {
                    AddResult(block, type);
                }

                base.VisitDNode(block);
                VisitChildren(block);
            }
        }
Ejemplo n.º 4
0
 public static void SortImports(DBlockNode scope, ITextDocument doc, bool separatePackageRoots = false)
 {
     foreach (var kv in CalculateImportsToSort(scope))
     {
         ResortImports(kv.Value, doc, kv.Key, separatePackageRoots);
     }
 }
Ejemplo n.º 5
0
            public override void VisitBlock(DBlockNode block)
            {
                VisitChildren(block);
                VisitDNode(block);

                if (block.StaticStatements.Count != 0)
                {
                    foreach (var s in block.StaticStatements)
                    {
                        if (s.Location > caret)
                        {
                            break;
                        }

                        s.Accept(this);
                    }
                }

                if (block.MetaBlocks.Count != 0)
                {
                    foreach (var mb in block.MetaBlocks)
                    {
                        if (mb.Location > caret)
                        {
                            break;
                        }
                        mb.Accept(this);
                    }
                }
            }
Ejemplo n.º 6
0
 public static IStatement GetStatementAt(DBlockNode db, CodeLocation Where)
 {
     if (db.StaticStatements.Count != 0)
     {
         return(SearchRegionAt <IStatement> (i => db.StaticStatements [i], db.StaticStatements.Count, Where));
     }
     return(null);
 }
		public override void VisitBlock (DBlockNode bn)
		{
			var back = ctxt.ScopedBlock;
			if (bn != back) {
				ctxt.PushNewScope (bn);
				OnScopedBlockChanged (bn);
			}
			base.VisitBlock (bn);
			if(bn != back)
				ctxt.Pop ();
		}
Ejemplo n.º 8
0
        public void PushBlock(DBlockNode bn)
        {
            var back = ctxt.ScopedBlock;

            using (ctxt.Push(bn)) {
                if (ctxt.ScopedBlock != back)
                {
                    OnScopedBlockChanged(bn);
                }
                VisitBlock(bn);
            }
        }
		/// <summary>
		/// Calls VisitDNode already.
		/// </summary>
		public virtual void VisitBlock(DBlockNode block)
		{
			VisitChildren(block);
			VisitDNode(block);

			if (block.StaticStatements.Count != 0)
				foreach (var s in block.StaticStatements)
					s.Accept(this);

			if (block.MetaBlocks.Count != 0)
				foreach (var mb in block.MetaBlocks)
					mb.Accept(this);
		}
Ejemplo n.º 10
0
        public static void TestString(string literal, string content, bool ProvideObjModule = true)
        {
            ResolutionContext ctxt = null;

            var block = new DBlockNode();

            if (ProvideObjModule)
            {
                ctxt = ResolutionTests.CreateDefCtxt(ResolutionTests.CreateCache(), block);
            }
            else
            {
                ctxt = ResolutionTests.CreateDefCtxt(new ParseCacheView(new string[] { }), block);
            }

            var x = DParser.ParseExpression(literal);

            Assert.That(x, Is.TypeOf(typeof(IdentifierExpression)));
            var id = (IdentifierExpression)x;

            var v = Evaluation.EvaluateValue(x, ctxt);

            Assert.That(v, Is.TypeOf(typeof(ArrayValue)));
            var av = (ArrayValue)v;

            Assert.That(av.IsString, Is.True);

            Assert.AreEqual(av.StringValue, content);

            Assert.IsInstanceOfType(typeof(ArrayType), av.RepresentedType);
            var ar = (ArrayType)av.RepresentedType;

            switch (id.Subformat)
            {
            case LiteralSubformat.Utf8:
                Assert.AreEqual(ar.DeclarationOrExpressionBase.ToString(), "immutable(char)[]");
                break;

            case LiteralSubformat.Utf16:
                Assert.AreEqual(ar.DeclarationOrExpressionBase.ToString(), "immutable(wchar)[]");
                break;

            case LiteralSubformat.Utf32:
                Assert.AreEqual(ar.DeclarationOrExpressionBase.ToString(), "immutable(dchar)[]");
                break;

            default:
                Assert.Fail();
                return;
            }
        }
Ejemplo n.º 11
0
        public static DBlockNode ParseDeclDefs(string Code)
        {
            var p = Create(new StringReader(Code));

            p.Step();
            var block = new DBlockNode();

            while (!p.IsEOF)
            {
                p.DeclDef(block);
            }

            block.EndLocation = p.la.Location;
            return(block);
        }
Ejemplo n.º 12
0
        public override void VisitBlock(DBlockNode bn)
        {
            var back = ctxt.ScopedBlock;

            if (bn != back)
            {
                ctxt.PushNewScope(bn);
                OnScopedBlockChanged(bn);
            }
            base.VisitBlock(bn);
            if (bn != back)
            {
                ctxt.Pop();
            }
        }
Ejemplo n.º 13
0
        public override void VisitBlock(DBlockNode n)
        {
            if (!(n is DModule))
            {
                _resultRanges.Add(new FoldingRange
                {
                    StartLine      = n.BlockStartLocation.Line - 1,
                    StartCharacter = n.BlockStartLocation.Column - 1,
                    EndLine        = n.EndLocation.Line - 1,
                    EndCharacter   = n.EndLocation.Column - 1,
                    Kind           = FoldingRangeKind.Region
                });
            }

            HandleImportRanges(n.StaticStatements);

            base.VisitBlock(n);
        }
Ejemplo n.º 14
0
        public override void VisitBlock(DBlockNode block)
        {
            if (block is DModule)
            {
                base.VisitBlock(block);
                return;
            }

            FormatAttributedNode(block);

            EnforceBraceStyle(policy.TypeBlockBraces, block.BlockStartLocation, block.EndLocation.Line, block.EndLocation.Column - 1);

            curIndent.Push(IndentType.Block);

            base.VisitBlock(block);

            curIndent.Pop();

            EnsureBlankLinesAfter(block.EndLocation, policy.LinesAfterNode);
        }
Ejemplo n.º 15
0
            public override void VisitBlock(DBlockNode block)
            {
                // Check metablocks first
                if (block.MetaBlocks.Count != 0)
                {
                    foreach (var mb in block.MetaBlocks)
                    {
                        mb.Accept(this);
                    }
                }

                if (block.StaticStatements.Count != 0)
                {
                    foreach (var s in block.StaticStatements)
                    {
                        s.Accept(this);
                    }
                }

                VisitDNode(block); // visit declaration itself first
                VisitChildren(block);
            }
Ejemplo n.º 16
0
 public AbstractType Visit(DBlockNode dBlockNode)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 17
0
		// http://www.digitalmars.com/d/2.0/declaration.html

		bool CheckForStorageClasses(DBlockNode scope)
		{
			bool ret = false;
			while (IsStorageClass )
			{
				if (IsAttributeSpecifier()) // extern, align
					AttributeSpecifier(scope);
				else
				{
					Step();
					// Always allow more than only one property DAttribute
					if (!Modifier.ContainsAttribute(DeclarationAttributes.ToArray(), t.Kind))
						PushAttribute(new Modifier(t.Kind, t.Value) { Location = t.Location, EndLocation = t.EndLocation }, false);
				}
				ret = true;
			}
			return ret;
		}
Ejemplo n.º 18
0
		INode Constructor(DBlockNode scope,bool IsStruct)
		{
			Expect(This);
			var dm = new DMethod(){
				Parent = scope,
				SpecialType = DMethod.MethodType.Constructor,
				Location = t.Location,
				Name = DMethod.ConstructorIdentifier,
				NameLocation = t.Location
			};
			dm.Description = GetComments();
			LastParsedObject = dm;

			if (IsTemplateParameterList())
				TemplateParameterList(dm);

			// http://dlang.org/struct.html#StructPostblit
			if (IsStruct && laKind == (OpenParenthesis) && Peek(1).Kind == (This))
			{
				var dv = new DVariable();
				LastParsedObject = dv;
				dv.Parent = dm;
				dv.Name = "this";
				dm.Parameters.Add(dv);
				Step();
				Step();
				Expect(CloseParenthesis);
			}
			else
			{
				dm.Parameters = Parameters(dm);
			}

			// handle post argument attributes
			FunctionAttributes(dm);

			if (!IsEOF)
				LastParsedObject = dm;

			if (laKind == If)
				Constraint(dm);

			// handle post argument attributes
			FunctionAttributes(dm);

			if(IsFunctionBody)
				FunctionBody(dm);
			return dm;
		}
Ejemplo n.º 19
0
		IMetaDeclarationBlock AttributeBlock(DBlockNode module)
		{
			int popCount = DeclarationAttributes.Count;

			/*
			 * If there are attributes given, put their references into the meta block.
			 * Also, pop them from the declarationAttributes stack on to the block attributes so they will be assigned to all child items later on.
			 */

			IMetaDeclarationBlock metaDeclBlock;

			if (popCount != 0)
				metaDeclBlock = new AttributeMetaDeclarationBlock(DeclarationAttributes.ToArray()) { BlockStartLocation = la.Location };
			else
				metaDeclBlock = new MetaDeclarationBlock { BlockStartLocation = la.Location };

			while (DeclarationAttributes.Count > 0)
				BlockAttributes.Push(DeclarationAttributes.Pop());

			ClassBody(module, true, false);

			// Pop the previously pushed attributes back off the stack
			for (int i = popCount; i > 0; i--)
				BlockAttributes.Pop();

			// Store the meta block
			metaDeclBlock.EndLocation = t.EndLocation;
			if(module!=null)
				module.Add(metaDeclBlock);
			return metaDeclBlock;
		}
Ejemplo n.º 20
0
		private void AttributeSpecifier(DBlockNode scope)
		{
			DAttribute attr;
			if(IsAtAttribute)
				attr = AtAttribute(scope);
			else if (laKind == Pragma)
				 attr=_Pragma();
			else if(laKind == Deprecated)
			{
				Step();
				var loc = t.Location;
				IExpression lc = null;
				if(laKind == OpenParenthesis)
				{
					Step();
					lc = AssignExpression(scope);
					Expect(CloseParenthesis);
				}
				attr = new DeprecatedAttribute(loc, t.EndLocation, lc);
			}
			else
			{
				var m = new Modifier(laKind, la.Value) { Location = la.Location };
				attr = m;
				LastParsedObject = attr;
				if (laKind == Extern && Lexer.CurrentPeekToken.Kind == OpenParenthesis)
				{
					Step(); // Skip extern
					Step(); // Skip (
	
					TrackerVariables.ExpectingIdentifier = true;
					var sb = new StringBuilder ();
					while (!IsEOF && laKind != CloseParenthesis)
					{
						Step();
						sb.Append(t.ToString());

						TrackerVariables.ExpectingIdentifier = false;
	
						if (t.Kind == Identifier && laKind == Identifier)
							sb.Append(' ');
					}
	
					m.LiteralContent = sb.ToString();
	
					if (!Expect(CloseParenthesis))
						return;
				}
				else if (laKind == Align && Lexer.CurrentPeekToken.Kind == OpenParenthesis)
				{
					Step();
					Step();
					if (Expect(Literal))
						m.LiteralContent = new IdentifierExpression(t.LiteralValue, t.LiteralFormat);
	
					if (!Expect(CloseParenthesis))
						return;
				}
				else
					Step();
	
				m.EndLocation = t.EndLocation;
			}

			if (laKind == Colon)
				LastParsedObject = null;

			//TODO: What about these semicolons after e.g. a pragma? Enlist these attributes anyway in the meta decl list?
			if (laKind != Semicolon)
				AttributeTrail(scope, attr);
		}
Ejemplo n.º 21
0
 public ulong Visit(DBlockNode dBlockNode)
 {
     return(1000117);
 }
Ejemplo n.º 22
0
		static void GetDoneVersionDebugSpecs(ConditionSet cs, MutableConditionFlagSet l, DBlockNode m, ResolutionContext ctxt)
		{
			if (m.StaticStatements == null || m.StaticStatements.Count == 0)
				return;

			foreach(var ss in m.StaticStatements)
			{
				if(ss is VersionSpecification)
				{
					var vs = (VersionSpecification)ss;
					
					if(!_checkForMatchinSpecConditions(m,cs,ss,ctxt))
						continue;
					
					if(vs.SpecifiedId==null)
 						l.AddVersionCondition(vs.SpecifiedNumber);
					else
						l.AddVersionCondition(vs.SpecifiedId);
				}
				else if(ss is DebugSpecification)
				{
					var ds = (DebugSpecification)ss;

					if(!_checkForMatchinSpecConditions(m,cs,ss, ctxt))
						continue;
					
					if (ds.SpecifiedId == null)
						l.AddDebugCondition(ds.SpecifiedDebugLevel);
					else
						l.AddDebugCondition(ds.SpecifiedId);
				}
			}
		}
        /// <returns>Either CurrentScope, a BlockStatement object that is associated with the parent method or a complete new DModule object</returns>
        public static object FindCurrentCaretContext(string code,
                                                     IBlockNode CurrentScope,
                                                     int caretOffset, CodeLocation caretLocation,
                                                     out ParserTrackerVariables TrackerVariables)
        {
            bool ParseDecl = false;

            int blockStart         = 0;
            var blockStartLocation = CurrentScope.BlockStartLocation;

            if (CurrentScope is DMethod)
            {
                var block = (CurrentScope as DMethod).GetSubBlockAt(caretLocation);

                if (block != null)
                {
                    blockStart = DocumentHelper.LocationToOffset(code, blockStartLocation = block.Location);
                }
                else
                {
                    return(FindCurrentCaretContext(code, CurrentScope.Parent as IBlockNode, caretOffset, caretLocation, out TrackerVariables));
                }
            }
            else if (CurrentScope != null)
            {
                if (CurrentScope.BlockStartLocation.IsEmpty || caretLocation < CurrentScope.BlockStartLocation && caretLocation > CurrentScope.Location)
                {
                    ParseDecl  = true;
                    blockStart = DocumentHelper.LocationToOffset(code, blockStartLocation = CurrentScope.Location);
                }
                else
                {
                    blockStart = DocumentHelper.LocationToOffset(code, CurrentScope.BlockStartLocation);
                }
            }

            if (blockStart >= 0 && caretOffset - blockStart > 0)
            {
                var codeToParse = code.Substring(blockStart, caretOffset - blockStart);

                var sr  = new StringReader(codeToParse);
                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);

                object ret = null;

                if (CurrentScope == null || CurrentScope is IAbstractSyntaxTree)
                {
                    ret = psr.Parse();
                }
                else if (CurrentScope is DMethod)
                {
                    psr.Step();
                    ret = psr.BlockStatement(CurrentScope);
                }
                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
                    {
                        DBlockNode bn = null;
                        if (CurrentScope is DClassLike)
                        {
                            var t = new DClassLike((CurrentScope as DClassLike).ClassType);
                            t.AssignFrom(CurrentScope);
                            bn = t;
                        }
                        else if (CurrentScope is DEnum)
                        {
                            var t = new DEnum();
                            t.AssignFrom(CurrentScope);
                            bn = t;
                        }

                        bn.Clear();

                        psr.ClassBody(bn);
                        ret = bn;
                    }
                }

                TrackerVariables = psr.TrackerVariables;
                sr.Close();

                return(ret);
            }

            TrackerVariables = null;

            return(null);
        }
Ejemplo n.º 24
0
 public string Visit(DBlockNode dBlockNode)
 {
     return(InvalidType);
 }
Ejemplo n.º 25
0
        /// <param name="scope"></param>
        /// <returns>A sorted list of imports that have their mutual attributes enlisted as the key.</returns>
        static List <KeyValuePair <List <DAttribute>, List <ImportStatement> > > CalculateImportsToSort(DBlockNode scope)
        {
            // Get the first scope that contains import statements
            var importsToSort = new List <ImportStatement> ();

            var allSharedAttrs = new List <DAttribute>();

            foreach (var mb in scope.MetaBlocks)
            {
                var mba = mb as AttributeMetaDeclaration;
                if (mba == null)
                {
                    continue;
                }
                else if (mba is AttributeMetaDeclarationSection)
                {
                    allSharedAttrs.AddRange(mba.AttributeOrCondition);
                }
                else if (mba is AttributeMetaDeclarationBlock)
                {
                    allSharedAttrs.AddRange(mba.AttributeOrCondition);
                }
                //TODO: Else-attributes
            }

            while (scope != null && importsToSort.Count == 0)
            {
                foreach (var ss in scope.StaticStatements)
                {
                    var iss = ss as ImportStatement;
                    if (iss != null)
                    {
                        importsToSort.Add(iss);
                    }
                }
            }

            if (importsToSort.Count < 2)
            {
                return(new List <KeyValuePair <List <DAttribute>, List <ImportStatement> > >());
            }

            // Split imports into groups divided by shared attributes
            var impDict       = new Dictionary <List <DAttribute>, List <ImportStatement> > ();
            var noAttrImports = new List <ImportStatement> ();

            foreach (var ii in importsToSort)
            {
                if (ii.Attributes == null || ii.Attributes.Length == 0)
                {
                    noAttrImports.Add(ii);
                    continue;
                }

                var sharedAttrs = new List <DAttribute>(ii.Attributes.Intersect(allSharedAttrs));
                if (sharedAttrs.Count == 0)
                {
                    continue;
                }

                bool hasAdded = false;

                foreach (var kv in impDict)
                {
                    if (kv.Key.Count > sharedAttrs.Count ||
                        kv.Key.Any((e) => !sharedAttrs.Contains(e)))
                    {
                        continue;
                    }

                    if (kv.Key.Count == sharedAttrs.Count)
                    {
                        if (!kv.Value.Contains(ii))
                        {
                            kv.Value.Add(ii);
                        }
                        hasAdded = true;
                        break;
                    }

                    kv.Value.Remove(ii);
                }

                if (!hasAdded)
                {
                    impDict.Add(sharedAttrs, new List <ImportStatement> {
                        ii
                    });
                }
            }

            impDict.Add(new List <DAttribute>(), noAttrImports);

            // Sort impDict entries by their at last occurring shared attribute
            var impDictList = impDict.ToList();

            impDictList.Sort(new ImportDictComparer());

            return(impDictList);
        }
Ejemplo n.º 26
0
 public static void UpdateBlockPartly(this DBlockNode bn, IEditorData ed, out bool isInsideNonCodeSegment)
 {
     UpdateBlockPartly(bn, ed.ModuleCode, ed.CaretOffset, ed.CaretLocation, out isInsideNonCodeSegment);
 }
Ejemplo n.º 27
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="module"></param>
		/// <param name="previouslyParsedAttribute"></param>
		/// <param name="RequireDeclDef">If no colon and no open curly brace is given as lookahead, a DeclDef may be parsed otherwise, if parameter is true.</param>
		/// <returns></returns>
		IMetaDeclaration AttributeTrail(DBlockNode module, DAttribute previouslyParsedAttribute, bool RequireDeclDef = false)
		{
			if (laKind == Colon)
			{
				Step();
				PushAttribute(previouslyParsedAttribute, true);

				AttributeMetaDeclarationSection metaDecl = null;
				//TODO: Put all remaining block/decl(?) attributes into the section definition..
				if(module!=null)
					module.Add(metaDecl = new AttributeMetaDeclarationSection(previouslyParsedAttribute) { EndLocation = t.EndLocation });
				return metaDecl;
			}
			else 
				PushAttribute(previouslyParsedAttribute, false);

			if (laKind == OpenCurlyBrace)
				return AttributeBlock(module);
			else
			{
				if (RequireDeclDef)
					DeclDef(module);
				return new AttributeMetaDeclaration(previouslyParsedAttribute) { EndLocation = previouslyParsedAttribute.EndLocation };
			}
		}
Ejemplo n.º 28
0
        public static void UpdateBlockPartly(this DBlockNode bn, string code,
                                             int caretOffset, CodeLocation caretLocation, out bool isInsideNonCodeSegment)
        {
            isInsideNonCodeSegment = false;

            // Get the end location of the declaration that appears before the caret.
            var startLoc = bn.BlockStartLocation;
            int startDeclIndex;

            for (startDeclIndex = bn.Children.Count - 1; startDeclIndex >= 0; startDeclIndex--)
            {
                var n = bn.Children [startDeclIndex];
                if (n.EndLocation.Line > 0 && n.EndLocation.Line < caretLocation.Line)
                {
                    startLoc = --startDeclIndex == -1 ?
                               bn.BlockStartLocation : bn.Children [startDeclIndex].EndLocation;
                    break;
                }
            }

            var startOff = startLoc.Line > 1 ? DocumentHelper.GetOffsetByRelativeLocation(code, caretLocation, caretOffset, startLoc) : 0;

            // Immediately break to waste no time if there's nothing to parse
            if (startOff >= caretOffset)
            {
                return;
            }

            // Get meta block stack so they can be registered while parsing
            //var metaDecls = bn.GetMetaBlockStack (startLoc, true, false);

            // Parse region from start until caret for maximum efficiency
            var tempBlock = bn is DEnum ? new DEnum() : new DBlockNode();

            try{
                using (var sv = new StringView(code, startOff, caretOffset - startOff))
                    using (var p = DParser.Create(sv)) {
                        p.Lexer.SetInitialLocation(startLoc);
                        p.Step();

                        if (p.laKind == DTokens.OpenCurlyBrace)
                        {
                            p.Step();
                        }

                        // Enum bodies
                        if (bn is DEnum)
                        {
                            do
                            {
                                if (p.laKind == DTokens.Comma)
                                {
                                    p.Step();
                                }
                                var laBackup = p.la;
                                p.EnumValue(tempBlock as DEnum);
                                if (p.la == laBackup)
                                {
                                    break;
                                }
                            }while(!p.IsEOF);
                        }
                        else                 // Normal class/module bodies
                        {
                            if (p.laKind == DTokens.Module && bn is DModule)
                            {
                                tempBlock.Add(p.ModuleDeclaration());
                            }

                            while (!p.IsEOF)
                            {
                                //
                                if (p.laKind == DTokens.CloseCurlyBrace)
                                {
                                    p.Step();

                                    /*if (metaDecls.Count > 0)
                                     *      metaDecls.RemoveAt (metaDecls.Count - 1);*/
                                    continue;
                                }

                                p.DeclDef(tempBlock);
                            }
                        }

                        // Update the actual tempBlock as well as methods/other blocks' end location that just appeared while parsing the code incrementally,
                        // so they are transparent to SearchBlockAt
                        var block = tempBlock as IBlockNode;
                        while (block != null &&
                               (block.EndLocation.Line < 1 || block.EndLocation == p.la.Location))
                        {
                            block.EndLocation = new CodeLocation(p.la.Column + 1, p.la.Line);
                            if (block.Children.Count == 0)
                            {
                                break;
                            }
                            block = block.Children[block.Count - 1] as IBlockNode;
                        }

                        if (isInsideNonCodeSegment = p.Lexer.endedWhileBeingInNonCodeSequence)
                        {
                            return;
                        }
                    }
            }catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

            // Remove old static stmts, declarations and meta blocks from bn
            /*bn.MetaBlocks;*/
            int startStatStmtIndex;

            for (startStatStmtIndex = bn.StaticStatements.Count - 1; startStatStmtIndex >= 0; startStatStmtIndex--)
            {
                var ss = bn.StaticStatements [startStatStmtIndex];
                if (ss.Location >= startLoc && ss.Location <= caretLocation)
                {
                    bn.StaticStatements.RemoveAt(startStatStmtIndex);
                }
                else if (ss.EndLocation < startLoc)
                {
                    break;
                }
            }

            INode ch_;
            int   i = startDeclIndex + 1;

            while (i < bn.Count && (ch_ = bn.Children [i]).Location < caretLocation)
            {
                bn.Children.Remove(ch_);
            }

            // Insert new static stmts, declarations and meta blocks(?) into bn
            if (tempBlock.EndLocation > bn.EndLocation)
            {
                bn.EndLocation = tempBlock.EndLocation;
            }
            foreach (var n in tempBlock.Children)
            {
                if (n != null)
                {
                    n.Parent = bn;
                    bn.Children.Insert(n, ++startDeclIndex);
                }
            }

            bn.StaticStatements.InsertRange(startStatStmtIndex + 1, tempBlock.StaticStatements);
        }
Ejemplo n.º 29
0
		public void ClassBody(DBlockNode ret,bool KeepBlockAttributes=false,bool UpdateBoundaries=true)
		{
			var OldPreviousCommentString = PreviousComment;
			PreviousComment = new StringBuilder ();

			if (Expect(OpenCurlyBrace))
			{
				var stk_backup = BlockAttributes;

				if(!KeepBlockAttributes)
					BlockAttributes = new Stack<DAttribute>();

				if(UpdateBoundaries)
					ret.BlockStartLocation = t.Location;

				while (!IsEOF && laKind != (CloseCurlyBrace))
				{
					DeclDef(ret);
				}

				if (!IsEOF)
					LastParsedObject = ret;

				if (Expect(CloseCurlyBrace))
					LastParsedObject = null;

				if(UpdateBoundaries)
					ret.EndLocation = t.EndLocation;

				if(!KeepBlockAttributes)
					BlockAttributes = stk_backup;
			}

			PreviousComment = OldPreviousCommentString;

			if(ret!=null)
				ret.Description += CheckForPostSemicolonComment();
		}
Ejemplo n.º 30
0
		protected bool scanChildren(DBlockNode curScope, 
									MemberFilter VisibleMembers,
									bool publicImports = false,
									bool isBaseClass = false,
									bool isMixinAst = false,
									bool takeStaticChildrenOnly = false,
		                            bool scopeIsInInheritanceHierarchy =false)
		{
			bool foundItems = false;

			//ConditionsStack.Push (new ConditionsFrame (curScope.StaticStatements, curScope.MetaBlocks));

			var ch = PrefilterSubnodes(curScope);
			if (ch != null)
				foreach (var n in ch)
				{
					//ContinueHandleStaticStatements (n.Location);

					if (!CanHandleNode (n as DNode, VisibleMembers, isBaseClass, isMixinAst, takeStaticChildrenOnly, publicImports, scopeIsInInheritanceHierarchy))
						continue;

					// Add anonymous enums' items
					if (n is DEnum && n.NameHash == 0)
					{
						var ch2 = PrefilterSubnodes(n as DEnum);
						if (ch2 != null)
							foundItems |= HandleItems(ch2);
						continue;
					}

					foundItems |= HandleItem(n);
				}

			if (foundItems) {
				//ConditionsStack.Pop ();
				return true;
			}

			if (!dontHandleTemplateParamsInNodeScan)
			{
				if (curScope.TemplateParameters != null && (VisibleMembers & MemberFilter.TypeParameters) != 0)
				{
					var t = ctxt.ScopedBlock;
					while (t != null)
					{
						if (t == curScope)
						{
							if (HandleItems (curScope.TemplateParameterNodes as IEnumerable<INode>)) {
								//ConditionsStack.Pop ();
								return true;
							}
							break;
						}
						t = t.Parent as IBlockNode;
					}
				}
			}
			else
				dontHandleTemplateParamsInNodeScan = false;

			//ContinueHandleStaticStatements (curScope.EndLocation);	ConditionsStack.Pop ();
			return HandleDBlockNode(curScope, VisibleMembers, publicImports);
		}
Ejemplo n.º 31
0
		void DeclarationCondition(DBlockNode module)
		{
			var sl = la.Location;

			var c = Condition(module);

			c.Location = sl;
			c.EndLocation = t.EndLocation;

			bool allowElse = laKind != Colon;

			var metaBlock = AttributeTrail(module, c, true) as AttributeMetaDeclaration;

			if (allowElse && metaBlock == null)
			{
				SynErr(t.Kind, "Wrong meta block type. (see DeclarationCondition();)");
				return;
			}
			else if (allowElse && laKind == Else)
			{
				Step();

				c = new NegatedDeclarationCondition(c);

				BlockAttributes.Push(c);
				if (laKind == OpenCurlyBrace)
				{
					metaBlock.OptionalElseBlock = new ElseMetaDeclarationBlock { Location = t.Location, BlockStartLocation = la.Location };
					ClassBody(module, true, false);
				}
				else
				{
					metaBlock.OptionalElseBlock = new ElseMetaDeclaration { Location = t.Location };
					DeclDef(module);
				}
				BlockAttributes.Pop();

				metaBlock.OptionalElseBlock.EndLocation = t.EndLocation;
			}
		}
Ejemplo n.º 32
0
		/// <summary>
		/// Handle the node's static statements (but not the node itself)
		/// </summary>
		bool HandleDBlockNode(DBlockNode dbn, MemberFilter VisibleMembers, bool takePublicImportsOnly = false)
		{
			bool foundItems = false;

			if (dbn != null && dbn.StaticStatements != null)
			{
				foreach (var stmt in dbn.StaticStatements)
				{
					var dstmt = stmt as IDeclarationContainingStatement;
					if (dstmt != null)
					{
						var impStmt = dstmt as ImportStatement;
						if ((takePublicImportsOnly && impStmt!=null && !impStmt.IsPublic) || 
						    !MatchesCompilationEnv(stmt) ||
						    impStmt.IsStatic)
							continue;

						/*
						 * Mainly used for selective imports/import module aliases
						 */
						if (dstmt.Declarations != null)
							foreach (var d in dstmt.Declarations)
								foundItems |= HandleItem(d); //TODO: Handle visibility?

						if (impStmt!=null)
						{
							foreach (var imp in impStmt.Imports)
								if (imp.ModuleAlias == null)
									foundItems |= HandleNonAliasedImport(imp, VisibleMembers);
						}
					}
					else if(stmt is MixinStatement)
					{
						if(MatchesCompilationEnv(stmt))
							foundItems |= HandleMixin(stmt as MixinStatement,true,VisibleMembers);
					}
					else if(stmt is TemplateMixin)
					{
						if (MatchesCompilationEnv(stmt))
							foundItems |= HandleUnnamedTemplateMixin(stmt as TemplateMixin, true, VisibleMembers);
					}
				}
			}

			// Every module imports 'object' implicitly
			if (dbn is DModule && !takePublicImportsOnly)
				foundItems |= HandleNonAliasedImport(_objectImport, VisibleMembers);

			return foundItems;
		}
Ejemplo n.º 33
0
        protected bool scanChildren(DBlockNode curScope,
                                    MemberFilter VisibleMembers,
                                    bool publicImports                 = false,
                                    bool isBaseClass                   = false,
                                    bool isMixinAst                    = false,
                                    bool takeStaticChildrenOnly        = false,
                                    bool scopeIsInInheritanceHierarchy = false)
        {
            bool foundItems = false;

            //ConditionsStack.Push (new ConditionsFrame (curScope.StaticStatements, curScope.MetaBlocks));

            var ch = PrefilterSubnodes(curScope);

            if (ch != null)
            {
                foreach (var n in ch)
                {
                    //ContinueHandleStaticStatements (n.Location);

                    if (!CanHandleNode(n as DNode, VisibleMembers, isBaseClass, isMixinAst, takeStaticChildrenOnly, publicImports, scopeIsInInheritanceHierarchy))
                    {
                        continue;
                    }

                    // Add anonymous enums' items
                    if (n is DEnum && n.NameHash == 0)
                    {
                        var ch2 = PrefilterSubnodes(n as DEnum);
                        if (ch2 != null)
                        {
                            foundItems |= HandleItems(ch2);
                        }
                        continue;
                    }

                    foundItems |= HandleItem(n);
                }
            }

            if (foundItems)
            {
                //ConditionsStack.Pop ();
                return(true);
            }

            if (!dontHandleTemplateParamsInNodeScan)
            {
                if (curScope.TemplateParameters != null && (VisibleMembers & MemberFilter.TypeParameters) != 0)
                {
                    var t = ctxt.ScopedBlock;
                    while (t != null)
                    {
                        if (t == curScope)
                        {
                            if (HandleItems(curScope.TemplateParameterNodes as IEnumerable <INode>))
                            {
                                //ConditionsStack.Pop ();
                                return(true);
                            }
                            break;
                        }
                        t = t.Parent as IBlockNode;
                    }
                }
            }
            else
            {
                dontHandleTemplateParamsInNodeScan = false;
            }

            //ContinueHandleStaticStatements (curScope.EndLocation);	ConditionsStack.Pop ();
            return(HandleDBlockNode(curScope, VisibleMembers, publicImports));
        }
Ejemplo n.º 34
0
 static bool _checkForMatchinSpecConditions(DBlockNode m, ConditionSet cs, StaticStatement ss, ResolutionContext ctxt)
 {
     return(ss.Attributes == null || cs.IsMatching(ss.Attributes, ctxt));
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Handle the node's static statements (but not the node itself)
        /// </summary>
        bool HandleDBlockNode(DBlockNode dbn, MemberFilter VisibleMembers, bool takePublicImportsOnly = false)
        {
            bool foundItems = false;

            if (dbn != null && dbn.StaticStatements != null)
            {
                foreach (var stmt in dbn.StaticStatements)
                {
                    var dstmt = stmt as IDeclarationContainingStatement;
                    if (dstmt != null)
                    {
                        var impStmt = dstmt as ImportStatement;
                        if ((takePublicImportsOnly && impStmt != null && !impStmt.IsPublic) ||
                            !MatchesCompilationEnv(stmt) ||
                            impStmt.IsStatic)
                        {
                            continue;
                        }

                        /*
                         * Mainly used for selective imports/import module aliases
                         */
                        if (dstmt.Declarations != null)
                        {
                            foreach (var d in dstmt.Declarations)
                            {
                                foundItems |= HandleItem(d);                                 //TODO: Handle visibility?
                            }
                        }
                        if (impStmt != null)
                        {
                            foreach (var imp in impStmt.Imports)
                            {
                                if (imp.ModuleAlias == null)
                                {
                                    foundItems |= HandleNonAliasedImport(imp, VisibleMembers);
                                }
                            }
                        }
                    }
                    else if (stmt is MixinStatement)
                    {
                        if (MatchesCompilationEnv(stmt))
                        {
                            foundItems |= HandleMixin(stmt as MixinStatement, true, VisibleMembers);
                        }
                    }
                    else if (stmt is TemplateMixin)
                    {
                        if (MatchesCompilationEnv(stmt))
                        {
                            foundItems |= HandleUnnamedTemplateMixin(stmt as TemplateMixin, true, VisibleMembers);
                        }
                    }
                }
            }

            // Every module imports 'object' implicitly
            if (dbn is DModule && !takePublicImportsOnly)
            {
                foundItems |= HandleNonAliasedImport(_objectImport, VisibleMembers);
            }

            return(foundItems);
        }
Ejemplo n.º 36
0
 public static IBlockNode UpdateBlockPartly(this DBlockNode bn, string code, int caretOffset, CodeLocation caretLocation, out bool isInsideNonCodeSegment)
 {
     return(new IncrBlockNodeParsing().ParseIncrementally(bn, code, caretOffset, caretLocation, out isInsideNonCodeSegment));
 }
Ejemplo n.º 37
0
 public IconId Visit(DBlockNode dBlockNode)
 {
     return(IconId.Null);
 }
		public override void VisitBlock(DBlockNode block)
		{
			if(block is DModule)
			{
				base.VisitBlock(block);
				return;
			}
			
			FormatAttributedNode(block);
			
			EnforceBraceStyle(policy.TypeBlockBraces, block.BlockStartLocation, block.EndLocation.Line, block.EndLocation.Column-1);
			
			curIndent.Push(IndentType.Block);
			
			base.VisitBlock(block);
			
			curIndent.Pop();
			
			EnsureBlankLinesAfter(block.EndLocation, policy.LinesAfterNode);
		}
Ejemplo n.º 39
0
 public CompletionItemKind Visit(DBlockNode n)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 40
0
		void DeclDef(DBlockNode module)
		{
			//AttributeSpecifier
			while (IsAttributeSpecifier())
			{
				AttributeSpecifier(module);

				if (t.Kind == Colon || laKind == CloseCurlyBrace || IsEOF)
					return;
			}

			if (laKind == Semicolon)
			{
				LastParsedObject = null;
				Step();
				return;
			}

			//ImportDeclaration
			if (laKind == Import)
				module.Add(ImportDeclaration(module));

			//Constructor
			else if (laKind == (This))
				module.Add(Constructor(module, module is DClassLike ? ((DClassLike)module).ClassType == DTokens.Struct : false));

			//Destructor
			else if (laKind == (Tilde) && Lexer.CurrentPeekToken.Kind == (This))
				module.Add(Destructor());

			//Invariant
			else if (laKind == (Invariant))
				module.Add(_Invariant());

			//UnitTest
			else if (laKind == (Unittest))
			{
				Step();
				var dbs = new DMethod(DMethod.MethodType.Unittest);
				ApplyAttributes(dbs);
				LastParsedObject = dbs;
				dbs.Location = t.Location;
				FunctionBody(dbs);
				dbs.EndLocation = t.EndLocation;
				module.Add(dbs);
			}

			/*
			 * VersionSpecification: 
			 *		version = Identifier ; 
			 *		version = IntegerLiteral ;
			 * 
			 * DebugSpecification: 
			 *		debug = Identifier ; 
			 *		debug = IntegerLiteral ;
			 */
			else if ((laKind == Version || laKind == Debug) && Peek(1).Kind == Assign)
			{
				DebugSpecification ds = null;
				VersionSpecification vs = null;

				if (laKind == Version)
					LastParsedObject = vs = new VersionSpecification { Location = la.Location, Attributes = GetCurrentAttributeSet_Array() };
				else
					LastParsedObject = ds = new DebugSpecification { Location = la.Location, Attributes = GetCurrentAttributeSet_Array() };
				
				Step();
				Step();

				if (laKind == Literal)
				{
					Step();
					if (t.LiteralFormat != LiteralFormat.Scalar)
						SynErr(t.Kind, "Integer literal expected!");
					try
					{
						if (vs != null)
							vs.SpecifiedNumber = Convert.ToInt32(t.LiteralValue);
						else
							ds.SpecifiedDebugLevel = Convert.ToInt32(t.LiteralValue);
					}
					catch { }
				}
				else if (laKind == Identifier)
				{
					Step();
					if (vs != null)
						vs.SpecifiedId = t.Value;
					else
						ds.SpecifiedId = t.Value;
				}
				else if (ds == null)
					Expect(Identifier);

				Expect(Semicolon);

				if (vs == null)
					ds.EndLocation = t.EndLocation;
				else
					vs.EndLocation = t.EndLocation;

				module.Add(vs as StaticStatement ?? ds);
			}

			else if (laKind == Version || laKind == Debug || (laKind == Static && Lexer.CurrentPeekToken.Kind == If))
				DeclarationCondition(module);

			//StaticAssert
			else if (laKind == (Assert))
			{
				Step();

				if (!Modifier.ContainsAttribute(DeclarationAttributes, Static))
					SynErr(Static, "Static assert statements must be explicitly marked as static");

				var ass = new StaticAssertStatement { Attributes = GetCurrentAttributeSet_Array(), Location = t.Location };

				if (Expect(OpenParenthesis))
				{
					ass.AssertedExpression = AssignExpression();
					if (laKind == (Comma))
					{
						Step();
						ass.Message = AssignExpression();
					}
					if(Expect(CloseParenthesis))
						Expect(Semicolon);
				}

				ass.EndLocation = t.EndLocation;

				module.Add(ass);
			}

			//TemplateMixinDeclaration
			else if (laKind == Mixin)
			{
				if (Peek(1).Kind == Template)
					module.Add(TemplateDeclaration(module));

				//TemplateMixin
				else if (Lexer.CurrentPeekToken.Kind == Identifier)
				{
					var tmx = TemplateMixin(module);
					if(tmx.MixinId==null)
						module.Add(tmx);
					else
						module.Add(new NamedTemplateMixinNode(tmx));
				}

				//MixinDeclaration
				else if (Lexer.CurrentPeekToken.Kind == OpenParenthesis)
					module.Add(MixinDeclaration(module,null));
				else
				{
					Step();
					SynErr(Identifier);
				}
			}

			// {
			else if (laKind == (OpenCurlyBrace))
				AttributeBlock(module);

			// Class Allocators
			// Note: Although occuring in global scope, parse it anyway but declare it as semantic nonsense;)
			else if (laKind == (New))
			{
				Step();

				var dm = new DMethod(DMethod.MethodType.Allocator) { Location = t.Location };
				ApplyAttributes(dm);

				dm.Parameters = Parameters(dm);
				FunctionBody(dm);
				dm.EndLocation = t.EndLocation;
				module.Add(dm);
			}

			// Class Deallocators
			else if (laKind == Delete)
			{
				Step();

				var dm = new DMethod(DMethod.MethodType.Deallocator) { Location = t.Location };
				dm.Name = "delete";
				ApplyAttributes(dm);

				dm.Parameters = Parameters(dm);
				FunctionBody(dm);
				dm.EndLocation = t.EndLocation;
				module.Add(dm);
			}

			// else:
			else
			{
				var decls = Declaration(module);
				if(module != null && decls!=null)
					module.AddRange(decls);
			}
		}
Ejemplo n.º 41
0
        static void GetDoneVersionDebugSpecs(ConditionSet cs, MutableConditionFlagSet l, DBlockNode m, ResolutionContext ctxt)
        {
            if (m.StaticStatements == null || m.StaticStatements.Count == 0)
            {
                return;
            }

            foreach (var ss in m.StaticStatements)
            {
                if (ss is VersionSpecification)
                {
                    var vs = (VersionSpecification)ss;

                    if (!_checkForMatchinSpecConditions(m, cs, ss, ctxt))
                    {
                        continue;
                    }

                    if (vs.SpecifiedId == null)
                    {
                        l.AddVersionCondition(vs.SpecifiedNumber);
                    }
                    else
                    {
                        l.AddVersionCondition(vs.SpecifiedId);
                    }
                }
                else if (ss is DebugSpecification)
                {
                    var ds = (DebugSpecification)ss;

                    if (!_checkForMatchinSpecConditions(m, cs, ss, ctxt))
                    {
                        continue;
                    }

                    if (ds.SpecifiedId == null)
                    {
                        l.AddDebugCondition(ds.SpecifiedDebugLevel);
                    }
                    else
                    {
                        l.AddDebugCondition(ds.SpecifiedId);
                    }
                }
            }
        }
Ejemplo n.º 42
0
		static bool _checkForMatchinSpecConditions(DBlockNode m,ConditionSet cs,StaticStatement ss, ResolutionContext ctxt)
		{
			return ss.Attributes == null || cs.IsMatching(ss.Attributes,ctxt);
		}
Ejemplo n.º 43
0
 public static IBlockNode UpdateBlockPartly(this DBlockNode bn, IEditorData ed, out bool isInsideNonCodeSegment)
 {
     return(new IncrBlockNodeParsing().ParseIncrementally(bn, ed, out isInsideNonCodeSegment));
 }
Ejemplo n.º 44
0
 public byte Visit(DBlockNode dBlockNode)
 {
     return(0);
 }