Click here to Skip to main content
12,349,355 members (71,005 online)
Click here to Skip to main content

Tagged as

Stats

7.5K views
375 downloads
13 bookmarked
Posted

Resolving Symbolic References in a CodeDOM (Part 7)

, 2 Dec 2012 CDDL
Resolving symbolic references in a CodeDOM.
Mono.Cecil.dll
Nova.CLI.exe
Nova.CodeDOM.dll
Nova.Examples.exe
Nova.Studio.exe
Nova.Test.exe
Nova.UI.dll
Nova.CLI
Properties
Nova.CodeDOM
CodeDOM
Annotations
Base
Comments
Base
DocComments
CodeRef
Base
List
Name
Base
Other
Simple
CompilerDirectives
Base
Conditionals
Base
Messages
Base
Pragmas
Base
Symbols
Base
Base
Interfaces
Expressions
AnonymousMethods
Base
Operators
Base
Binary
Arithmetic
Base
Assignment
Base
Bitwise
Base
Conditional
Relational
Base
Shift
Base
Other
Base
Unary
Base
Other
References
Base
GotoTargets
Base
Methods
Namespaces
Other
Properties
Types
Base
Variables
Base
Projects
Assemblies
Namespaces
References
Base
Statements
Base
Conditionals
Base
Exceptions
Generics
Constraints
Base
Iterators
Base
Jumps
Loops
Methods
OperatorDecls
Miscellaneous
Namespaces
Properties
Base
Events
Types
Base
Variables
Base
Parsing
Base
Properties
Rendering
Resolving
Utilities
Mono.Cecil
Reflection
Nova.Examples
Properties
Nova.Studio
Images
About.png
Configuration.png
EditCopy.png
EditCut.png
EditDelete.png
EditPaste.png
EditRedo.png
EditUndo.png
Error.png
Exit.png
FileNew.png
FileOpen.png
FileSave.png
FileSaveAll.png
FileSaveAs.png
Find.png
Help.png
Info.png
Logo.png
Options.png
Print.png
PrintPreview.png
Properties.png
Todo.png
Warning.png
Objects.ico
Properties
Nova.Test
Properties
Nova.UI
CodeDOM
Annotations
Base
Comments
Base
DocComments
CodeRef
Base
List
Name
Base
Other
Simple
CompilerDirectives
Base
Conditionals
Base
Messages
Base
Pragmas
Base
Symbols
Base
Base
Expressions
AnonymousMethods
Base
Operators
Base
Binary
Arithmetic
Base
Assignment
Base
Bitwise
Base
Conditional
Relational
Base
Shift
Base
Other
Base
Unary
Base
Other
References
Base
GotoTargets
Base
Methods
Namespaces
Other
Properties
Types
Base
Variables
Base
Projects
Namespaces
References
Base
Statements
Base
Conditionals
Base
Exceptions
Generics
Constraints
Base
Iterators
Base
Jumps
Loops
Methods
OperatorDecls
Miscellaneous
Namespaces
Properties
Base
Events
Types
Base
Variables
Base
Properties
Resolving
Utilties
// The Nova Project by Ken Beckett.
// Copyright (C) 2007-2012 Inevitable Software, all rights reserved.
// Released under the Common Development and Distribution License, CDDL-1.0: http://opensource.org/licenses/cddl1.php

using Nova.Parsing;
using Nova.Rendering;
using Nova.Resolving;

namespace Nova.CodeDOM
{
    /// <summary>
    /// Represents a block of code in a documentation comment.
    /// </summary>
    public class DocCode : DocComment, IBlock
    {
        #region /* STATIC FIELDS */

        /// <summary>
        /// Determines if <see cref="DocCode"/> content is parsed as code or plain text.
        /// </summary>
        public static bool ParseContentAsCode = true;

        #endregion

        #region /* CONSTRUCTORS */

        /// <summary>
        /// Create a <see cref="DocCode"/>.
        /// </summary>
        public DocCode(CodeObject content)
            : base(content)
        { }

        #endregion

        #region /* STATIC CONSTRUCTOR */

        static DocCode()
        {
            // Force a reference to CodeObject to trigger the loading of any config file if it hasn't been done yet
            ForceReference();
        }

        #endregion

        #region /* PROPERTIES */

        /// <summary>
        /// The XML tag name for the documentation comment.
        /// </summary>
        public override string TagName
        {
            get { return ParseToken; }
        }

        /// <summary>
        /// The <see cref="Block"/> body.
        /// </summary>
        public Block Body
        {
            get { return _content as Block; }
            set
            {
                _content = value;
                if (_content != null)
                {
                    ((Block)_content).Parent = this;
                    ReformatBlock();
                }
            }
        }

        /// <summary>
        /// Always <c>false</c>.
        /// </summary>
        public bool HasHeader
        {
            get { return false; }
        }

        /// <summary>
        /// Always <c>true</c>.
        /// </summary>
        public bool IsTopLevel
        {
            get { return true; }
        }

        #endregion

        #region /* METHODS */

        /// <summary>
        /// Create a body if one doesn't exist yet.
        /// </summary>
        public Block CreateBody()
        {
            if (!(_content is Block))
                Body = new Block();
            return Body;
        }

        /// <summary>
        /// Add a <see cref="CodeObject"/> to the embedded code <see cref="Block"/>.
        /// </summary>
        public virtual void Add(CodeObject obj)
        {
            CreateBody().Add(obj);
        }

        /// <summary>
        /// Add multiple <see cref="CodeObject"/>s to the embedded code <see cref="Block"/>.
        /// </summary>
        public void Add(params CodeObject[] objects)
        {
            CreateBody();
            foreach (CodeObject obj in objects)
                Body.Add(obj);
        }

        /// <summary>
        /// Insert a <see cref="CodeObject"/> at the specified index.
        /// </summary>
        /// <param name="index">The index at which to insert.</param>
        /// <param name="obj">The object to be inserted.</param>
        public void Insert(int index, CodeObject obj)
        {
            CreateBody().Insert(index, obj);
        }

        /// <summary>
        /// Remove the specified <see cref="CodeObject"/> from the emedded code <see cref="Block"/>.
        /// </summary>
        public void Remove(CodeObject obj)
        {
            if (_content is Block)
                Body.Remove(obj);
        }

        /// <summary>
        /// Remove all objects from the embedded code <see cref="Block"/>.
        /// </summary>
        public void RemoveAll()
        {
            if (_content is Block)
                Body.RemoveAll();
        }

        /// <summary>
        /// Deep-clone the code object.
        /// </summary>
        public override CodeObject Clone()
        {
            DocCode clone = (DocCode)base.Clone();
            clone.CloneField(ref clone._content, _content);
            return clone;
        }

        #endregion

        #region /* PARSING */

        /// <summary>
        /// The token used to parse the code object.
        /// </summary>
        public new const string ParseToken = "code";

        internal static void AddParsePoints()
        {
            Parser.AddDocCommentParseTag(ParseToken, Parse);
        }

        /// <summary>
        /// Parse a <see cref="DocCode"/>.
        /// </summary>
        public static new DocComment Parse(Parser parser, CodeObject parent, ParseFlags flags)
        {
            DocCode docCode = new DocCode(parser, parent);
            if (AutomaticCodeCleanup && docCode.Content is Expression)
                return new DocC((Expression)docCode.Content);
            return docCode;
        }

        /// <summary>
        /// Parse a <see cref="DocCode"/>.
        /// </summary>
        public DocCode(Parser parser, CodeObject parent)
        {
            ParseTag(parser, parent);  // Ignore any attributes
        }

        protected override bool ParseContent(Parser parser)
        {
            // Parse the content as code unless disabled or the content is empty
            if (ParseContentAsCode && parser.Char != ParseTokenTagOpen[0])
            {
                // Override parsing of the content to parse as a code block until we hit "</code>"
                SetField(ref _content, parser.ParseCodeBlockUntil(ParseTokenTagOpen + ParseTokenEndTag + ParseToken + ParseTokenTagClose, this), false);

                // If the content is null, code parsing was aborted - fall through and parse as non-code instead
                if (_content != null)
                {
                    // Convert a single-line block without braces to the single statement
                    if (_content is Block)
                    {
                        Block block = (Block)_content;
                        if (block.Count == 1 && !block.HasBraces)
                            _content = block[0];
                    }

                    // Look for expected end tag
                    return (parser.InDocComment && ParseEndTag(parser));
                }
            }
            return base.ParseContent(parser);
        }

        #endregion

        #region /* RESOLVING */

        /// <summary>
        /// Resolve all child symbolic references, using the specified <see cref="ResolveCategory"/> and <see cref="ResolveFlags"/>.
        /// </summary>
        public override CodeObject Resolve(ResolveCategory resolveCategory, ResolveFlags flags)
        {
            if ((flags & (ResolveFlags.Phase1 | ResolveFlags.Phase2)) == 0)
            {
                // Resolve the embedded code with no phases - this should work for almost all sample code.  We could do it in 3 phases
                // to handle 100% of cases, but this would result in multiple resolves of expression-level references that fail (such
                // as non-code put inside the code comment).
                flags &= ~(ResolveFlags.Phase1 | ResolveFlags.Phase2 | ResolveFlags.Phase3);
                flags |= ResolveFlags.InDocComment;
                if (_content is ChildList<DocComment>)
                    ChildListHelpers.Resolve((ChildList<DocComment>)_content, ResolveCategory.CodeObject, flags);
                else if (_content is CodeObject)
                    _content = ((CodeObject)_content).Resolve(_content is Expression ? ResolveCategory.Expression : ResolveCategory.CodeObject, flags);
            }
            return this;
        }

        /// <summary>
        /// Resolve child code objects that match the specified name, moving up the tree until a complete match is found.
        /// </summary>
        public override void ResolveRefUp(string name, Resolver resolver)
        {
            if (_content is Block)
            {
                ((Block)_content).ResolveRef(name, resolver);
                if (resolver.HasCompleteMatch) return;  // Abort if we found a match
            }
            if (_parent != null)
                _parent.ResolveRefUp(name, resolver);
        }

        #endregion

        #region /* FORMATTING */

        /// <summary>
        /// Reformat the <see cref="Block"/> body.
        /// </summary>
        public void ReformatBlock()
        { }

        /// <summary>
        /// Default format the specified child field code object.
        /// </summary>
        protected override void DefaultFormatField(CodeObject field)
        {
            // Just default format the field by default - don't remove any newlines
            field.DefaultFormat();
        }

        #endregion

        #region /* RENDERING */

        protected override void AsTextContent(CodeWriter writer, RenderFlags flags)
        {
            if (_content is CodeObject)
            {
                // Adjust the starting indentation for the code to allow for the '/// ' prefix
                writer.BeginOutdentOnNewLine(this, writer.IndentOffset + 4);
                writer.AfterNewLine += AfterTextNewLine;
                base.AsTextContent(writer, flags);
                if (_content is Block || _content is BlockStatement)
                    writer.WriteLine();
                writer.AfterNewLine -= AfterTextNewLine;
                writer.EndIndentation(this);
            }
            else
                base.AsTextContent(writer, flags);
        }

        protected void AfterTextNewLine(CodeWriter writer)
        {
            // Render the '///' prefix at the starting indent level, followed by any additional indentation
            int previousIndentPosition = writer.IndentOffset;
            int startingIndentPosition = writer.GetIndentOffset(this);
            writer.IndentOffset = startingIndentPosition - 4;  // Adjust for '/// ' prefix
            writer.Write(DocComment.ParseToken + " " + new string(' ', previousIndentPosition - startingIndentPosition));
            writer.IndentOffset = previousIndentPosition;
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)

Share

About the Author

KenBeckett
Software Developer (Senior)
United States United States
I've been writing software since the late 70's, currently focusing mainly on C#.NET. I also like to travel around the world, and I own a Chocolate Factory (sadly, none of my employees are oompa loompas).

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160621.1 | Last Updated 2 Dec 2012
Article Copyright 2012 by KenBeckett
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid