Esempio n. 1
0
		public static IEnumerable<XElement> Ancestors(this XNode node, XName name, bool ignoreNamespace)
		{
			if (ignoreNamespace)
				return node.Ancestors().Where(e => e.Name.LocalName == name.LocalName);
			else
				return node.Ancestors(name);
		}
	/// <summary>
	/// Returns a relative (logical) path between a node and an ancestor.
	/// </summary>
	/// <param name="descendent">The descendent node to calculate the relative path for.</param>
	/// <param name="ancestor">The ancestor node that determines the root of the relative path.</param>
	/// <returns>The relative path from <paramref name="ancestor"/> to <paramref name="descendent"/>.</returns>
	/// <exception cref="System.ArgumentException">The <paramref name="ancestor"/> node is not actually 
	/// an ancestor of <paramref name="descendent"/>.</exception>
	public static string RelativePathTo (this ISolutionExplorerNode descendent, ISolutionExplorerNode ancestor)
	{
		if (!descendent.Ancestors ().Any (node => node.Equals (ancestor) || ReferenceEquals(node, ancestor)))
			throw new ArgumentException (Strings.ISolutionExplorerNodeExtensions.NotAncestor (ancestor, descendent));

		return string.Join (Path.DirectorySeparatorChar.ToString (), descendent
			.Ancestors ()
			.TakeWhile (node => !node.Equals (ancestor) && !ReferenceEquals(node, ancestor))
			.Select (node => node.Name)
			.Reverse ()
			.Concat (new[] { descendent.Name }));
	}
        /// <summary> 
        /// Get the absolute XPath to a given XElement
        /// (e.g. "/people/person[6]/name[1]/last[1]").
        /// </summary> 
        /// <param name="element"> 
        /// The element to get the index of.
        /// </param> 
        public static string AbsoluteXPath(this XElement element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            Func<XElement, string> relativeXPath = e =>
            {
                int index = e.IndexPosition();
                string name = e.Name.LocalName;

                // If the element is the root, no index is required

                return (index == -1) ? "/" + "*[local-name()='" + name + "']" : string.Format
                (
                    "/*[local-name()='{0}'][{1}]",
                    name,
                    index.ToString()
                );
            };

            var ancestors = from e in element.Ancestors()
                            select relativeXPath(e);

            return string.Concat(ancestors.Reverse().ToArray()) +
                   relativeXPath(element);
        }
 public static bool IsEAPMethod(this InvocationExpressionSyntax invocation)
 {
     return invocation.Expression.ToString().ToLower().EndsWith("async") &&
            invocation.Ancestors().OfType<MethodDeclarationSyntax>().Any(node =>
                                                                    node.DescendantNodes()
                                                                    .OfType<BinaryExpressionSyntax>()
                                                                    .Any(a => a.Left.ToString().ToLower().EndsWith("completed")));
 }
Esempio n. 5
0
 public static IEnumerable<XElement> SafeAncestors(this XElement element)
 {
     if (element == null) {
         yield break;
     }
     foreach (var elem in element.Ancestors()) {
         yield return elem;
     }
 }
Esempio n. 6
0
        public static HtmlNode Ancestor(this HtmlNode node, string name)
        {
            foreach (var ancestor in node.Ancestors(name))
            {
                // .Ancestors(name) works by yield so
                // this performs just as well as .FirstOrDefault
                return ancestor;
            }

            return null;
        }
Esempio n. 7
0
        /// <summary>
        /// Gets the local declaration corresponding to the given name.
        /// </summary>
        /// <param name="name">A <see cref="SRC"/> element.</param>
        /// <returns>The corresponding declaration, null if not found.</returns>
        public static XElement GetLocalDecl(this XElement name)
        {
            if (null == name)
                throw new ArgumentNullException("name");

            SrcMLElement.ThrowExceptionOnInvalidName(name, SRC.Name);

            var decls = from d in name.Ancestors(SRC.Function).First().Descendants(SRC.Declaration)
                        where d.Elements(SRC.Name).Any()
                        where d.IsBefore(name) && d.Element(SRC.Name).Value == name.Value
                        select d;
            return decls.Last();
        }
Esempio n. 8
0
        public static IEnumerable<string> GetContainingNamespaces(this SyntaxNode node)
        {
            var list = new List<string>();
            foreach (var ns in node.Ancestors().OfType<NamespaceDeclarationSyntax>())
            {
                var name = ns.ChildNodes().First().ToString();
                list.AddRange(name.Split('.'));
            }

            for(int j = 1; j <= list.Count; ++j)
            {
                yield return list.Take(j).ToSeparatorList(".");
            }
        }
        public static SyntaxNode GetParentMethodBody(this ParameterSyntax parameter)
        {
            var parentMethod = parameter.Ancestors().FirstOrDefault(n => n is SimpleLambdaExpressionSyntax ||
                n is BaseMethodDeclarationSyntax ||
                n is ParenthesizedLambdaExpressionSyntax);

            if (parentMethod is BaseMethodDeclarationSyntax)
                return ((BaseMethodDeclarationSyntax)parentMethod).Body;
            else if (parentMethod is SimpleLambdaExpressionSyntax)
                return ((SimpleLambdaExpressionSyntax)parentMethod).Body;
            else if (parentMethod is ParenthesizedLambdaExpressionSyntax)
                return ((ParenthesizedLambdaExpressionSyntax)parentMethod).Body;
            else
                throw new InvalidOperationException("Unhandled expression syntax.");
        }
Esempio n. 10
0
        /// <summary>
        /// Returns a filtered collection of <see cref="XElement"/>s within the containing <see cref="XDocument"/>
        /// which are reachable from the given <see cref="XElement"/> when considering ref scope.
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        public static IEnumerable<XElement> RefElements(this XElement element)
        {
            Contract.Requires<ArgumentNullException>(element != null);

            // obtain root element
            var root = (XElement)element.AncestorsAndSelf()
                .Where(i => i.Interfaces<IRefRoot>().Any())
                .DefaultIfEmpty(element.Document.Root)
                .FirstOrDefault();

            // obtain all scopes this element is a member of
            var scopes = new HashSet<IRefScope>(element
                .Ancestors()
                .SelectMany(i => i.Interfaces<IRefScope>()));

            // return elements that share one of these scopes, and that are underneath the root
            foreach (var node in DescendantsAndSelfInRefScope(root, scopes))
                yield return node;
        }
Esempio n. 11
0
        public static string GetAbsoluteXPath(this XElement element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            Func<XElement, string> relativeXPath = e =>
            {
                var index = e.IndexPosition();
                var name = e.Name.LocalName;

                return (index == -1)
                    ? "/" + name
                    : string.Format("/{0}[{1}]", name, index.ToString(CultureInfo.InvariantCulture));
            };

            var ancestors = from e in element.Ancestors() select relativeXPath(e);

            return string.Concat(ancestors.Reverse().ToArray()) + relativeXPath(element);
        }
Esempio n. 12
0
        /// <summary>
        /// Get the absolute XPath to a given XElement, including the namespace.
        /// (e.g. "/a:people/b:person[6]/c:name[1]/d:last[1]").
        /// </summary>
        public static string GetAbsoluteXPath(this XElement element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            Func<XElement, string> relativeXPath = e =>
            {
                int index = e.IndexPosition();

                var currentNamespace = e.Name.Namespace;

                string name = "";
                if (currentNamespace == null)
                {
                    name = e.Name.LocalName;
                }
                else
                {
                    //string namespacePrefix = e.GetPrefixOfNamespace(currentNamespace);
                    name += "/"+ e.Name.LocalName;
                }

                return name;
                // If the element is the root, no index is required
                //return (index == -1) ? "/" + name : string.Format
                //(
                //    "/{0}[{1}]",
                //    name,
                //    index.ToString()
                //);
            };

            var ancestors = from e in element.Ancestors()
                            select relativeXPath(e);

            return string.Concat(ancestors.Reverse().ToArray()) +
                   relativeXPath(element);
        }
Esempio n. 13
0
        /// <summary>
        /// Returns the parent statement (either expr_stmt, or decl_stmt) of the given node.
        /// </summary>
        /// <param name="node">The node to search from.</param>
        /// <returns>the parent element for <paramref name="node"/>. It will be either <see cref="SRC.ExpressionStatement"/> or <see cref="SRC.DeclarationStatement"/></returns>
        public static XElement ParentStatement(this XNode node) {
            if(null == node)
                throw new ArgumentNullException("node");

            var ancestors = node.Ancestors().Where(a => a.Name.LocalName.EndsWith("_stmt", StringComparison.Ordinal));

            if(ancestors.Any())
                return ancestors.First();
            return null;
        }
 public static string[] GetUsedNamespaces(this SyntaxNode node)
 {
     return node.Ancestors().OfType<CompilationUnitSyntax>().First().DescendantNodes().
       OfType<UsingDirectiveSyntax>().Select(x => x.Name.ToString()).ToArray();
 }
 public static SyntaxNode FindCommonAncestor(this SyntaxToken token, SyntaxToken otherToken)
 {
     var otherTokenAncestors = otherToken.Ancestors().ToList();
     return token.Ancestors().FirstOrDefault(ancestor => otherTokenAncestors.Contains(ancestor));
 }
 public static ClassDeclarationSyntax GetParentClass(this SyntaxNode node)
 {
     return node.Ancestors().OfType<ClassDeclarationSyntax>().FirstOrDefault();
 }
 public static MemberDeclarationSyntax GetParentMethod(this SyntaxNode node)
 {
     return node.Ancestors().OfType<MemberDeclarationSyntax>().FirstOrDefault();
 }
		public static IEnumerable<IPublishedContent> Ancestors(this IPublishedContent content)
		{
			return content.Ancestors(n => true);
		}
Esempio n. 19
0
        /// <summary>Get first ancestor. Optionally, include self.</summary>
        /// <remarks>Extension method.</remarks>
        public static DynamicNode GetFirstAncestor(this DynamicNode cmsItem, string nodeTypeAlias, string pageName, bool includeSelf = false)
        {
            IList<DynamicNode> cmsItems = null;

            if(cmsItem != null) {
            if(includeSelf) {
                cmsItems = cmsItem.AncestorsOrSelf(nodeTypeAlias).Items;
            } else {
                cmsItems = cmsItem.Ancestors(nodeTypeAlias).Items;
            }
            return cmsItems.Where(x => x.Name == pageName).FirstOrDefault();
            }
            return null;
        }
		public static IEnumerable<IPublishedContent> Ancestors(this IPublishedContent content, string nodeTypeAlias)
		{
			return content.Ancestors(n => n.DocumentTypeAlias == nodeTypeAlias);
		}
Esempio n. 21
0
 public static bool HasAncestorKind(this SyntaxNode node, params SyntaxKind[] kinds)
 {
     return node.Ancestors().Any(n => kinds.Contains(n.Kind()));
 }
Esempio n. 22
0
		public static XElement GetAncestorCI(this XElement x, string elementName)
		{
			XElement result = x.Ancestors().Where(a => a.Name.LocalName.ToLower() == elementName).FirstOrDefault();
			return result;
		}
Esempio n. 23
0
 public static string DescribePath(this XElement e)
 {
     var up = e.Ancestors().Reverse().Select(a => a.DescribeSelector()).Join("/");
     var me = (up.IsBlank() ? "" : up + "/") + e.DescribeSelector();
     return me;
 }
        /// <summary>
        /// Gets the ancestors of the current Content entity relationships
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public static IEnumerable<File> AncestorsAsFile(this EntityRelationCollection collection)
        {
            Mandate.ParameterNotNull(collection, "collection");

            return collection.Ancestors<File>(FixedRelationTypes.FileRelationType);
        }
		public static bool IsDescendant(this IPublishedContent content, IPublishedContent other)
		{
			var ancestors = content.Ancestors();
			return content.IsHelper(n => ancestors.FirstOrDefault(ancestor => ancestor.Id == other.Id) != null);
		}
        public static HashSet<string> GetSurroundingPaths(
                this CstNode node, HashSet<CstNode> surroundingNodes, FeatureExtractor extractor,
                CstNode outermostNode) {
            var path = node.Name;
            var paths = new HashSet<string>();
            var ancestors = new Dictionary<CstNode, string> { { node, node.Name } };

            paths.Add(node.Name);
            //paths.Add("'" + extractor.GetToken(node));

            var ancestor = node.Ancestors().FirstOrDefault(a => a.Children().Count() > 1);
            if (surroundingNodes.Contains(ancestor)) {
                extractor.IsInner = false;

                var originalNode = node;
                path = node.Name + node.RuleId;
                while ((node = node.Parent) != outermostNode) {
                    ancestors.Add(node, path + "<" + node.Name);
                    path = path + "<" + node.Name + node.RuleId;
                    paths.Add(path);
                }
                path = path + "<" + node.Name; // must not have RuleId
                paths.Add(path);

                var index = 0;
                foreach (var tokenNode in
                        originalNode.PreviousTokenNodes(node).Where(IsMeaningfulIdentifier)) {
                    if (!surroundingNodes.Contains(tokenNode)) {
                        break;
                    }
                    paths.Add("'-" + extractor.GetToken(tokenNode));
                    index++;
                }
                extractor.TokenLeft = Math.Max(extractor.TokenLeft, index);
                index = 0;
                foreach (var tokenNode in 
                        originalNode.NextTokenNodes(node).Where(IsMeaningfulIdentifier)) {
                    if (!surroundingNodes.Contains(tokenNode)) {
                        break;
                    }
                    paths.Add("'+" + extractor.GetToken(tokenNode));
                    index++;
                }
                extractor.TokenRight = Math.Max(extractor.TokenRight, index);
            }
            GetSurroundingPaths(node, path, surroundingNodes, extractor, paths, ancestors);
            return paths;
        }
Esempio n. 27
0
        /// <summary>
        /// Gets the line of source code that contains the given element.
        /// <para>This differs from <see cref="GetXmlLineNumber"/> in that this is the number of lines relative
        /// to the current <see cref="SRC.Unit"/>; this matches to the line number in the original source file.</para>
        /// </summary>
        /// <param name="element">The element</param>
        /// <returns>The line of source code; -1 if that info is not found.</returns>
        public static int GetSrcLineNumber(this XElement element) {
            if(null == element)
                throw new ArgumentNullException("element");

            int lineNumber = -1;

            var srcLineAttribute = GetAttributeFromSelfOrDescendant(element, POS.Line);
            if(null != srcLineAttribute && Int32.TryParse(srcLineAttribute.Value, out lineNumber)) {
                return lineNumber;
            }

            int xmlLineNum = element.GetXmlLineNumber();

            // if no line info is present, just return -1
            // we may want to look at calculating the line number based on the text in the file (see GetSrcLinePosition below)
            if(-1 == xmlLineNum)
                return -1;

            // if th element is a unit, just return 0: Source line number doesn't make sense for a file.
            if(SRC.Unit == element.Name)
                return 1;

            // get the xml line number of the file unit that contains this element
            var unit = element.Ancestors(SRC.Unit).First();
            int fileStart = unit.GetXmlLineNumber();

            // the line number is just the difference between the xml line number and the xml line number of the unit
            lineNumber = xmlLineNum - fileStart + 1;
            return lineNumber;
        }
		public static HtmlString IsDescendant(this IPublishedContent content, IPublishedContent other, string valueIfTrue, string valueIfFalse)
		{
			var ancestors = content.Ancestors();
			return content.IsHelper(n => ancestors.FirstOrDefault(ancestor => ancestor.Id == other.Id) != null, valueIfTrue, valueIfFalse);
		}
        /*
         * Name Reduction, to implicitly mean "this", is possible only after the initialization of all member variables but
         * since the check for initialization of all member variable is a lot of work for this simplification we don't simplify
         * even if all the member variables are initialized
         */
        private static bool AccessMethodWithDynamicArgumentInsideStructConstructor(this MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel)
        {
            var constructor = memberAccess.Ancestors().OfType<ConstructorDeclarationSyntax>().SingleOrDefault();

            if (constructor == null || constructor.Parent.Kind() != SyntaxKind.StructDeclaration)
            {
                return false;
            }

            return semanticModel.GetSymbolInfo(memberAccess.Name).CandidateReason == CandidateReason.LateBound;
        }
		public static IEnumerable<IPublishedContent> Ancestors(this IPublishedContent content, int level)
		{
			return content.Ancestors(n => n.Level <= level);
		}