Click here to Skip to main content
11,502,559 members (64,861 online)
Click here to Skip to main content
Add your own
alternative version

Resolving Symbolic References in a CodeDOM (Part 7)

, 2 Dec 2012 CDDL 5.8K 335 13
Resolving symbolic references in a CodeDOM.
Nova.0.6.exe.zip
Mono.Cecil.dll
Nova.CLI.exe
Nova.CodeDOM.dll
Nova.Examples.exe
Nova.Studio.exe
Nova.Test.exe
Nova.UI.dll
Nova.0.6.zip
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
Settings.settings
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 System;
using System.Collections;
using System.Collections.Generic;

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

namespace Nova.CodeDOM
{
    /// <summary>
    /// Declares a type that represents a reference to a method.
    /// </summary>
    /// <remarks>
    /// A delegate has no visible body, but one is generated by the compiler to hold the
    /// compiler-generated BeginInvoke and EndInvoke methods.
    /// </remarks>
    public class DelegateDecl : TypeDecl, IParameters
    {
        #region /* FIELDS */

        /// <summary>
        /// The return type is an <see cref="Expression"/> that must evaluate to a <see cref="TypeRef"/> in valid code.
        /// </summary>
        protected Expression _returnType;

        protected ChildList<ParameterDecl> _parameters;

        #endregion

        #region /* CONSTRUCTORS */

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name and return type.
        /// </summary>
        public DelegateDecl(string name, Expression returnType, Modifiers modifiers)
            : base(name, modifiers, new Block { IsGenerated = true })
        {
            ReturnType = returnType;
            GenerateMethods();  // Generate invoke methods and constructor
        }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name and return type.
        /// </summary>
        public DelegateDecl(string name, Expression returnType)
            : this(name, returnType, Modifiers.None)
        { }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name, return type, modifiers, and parameters.
        /// </summary>
        public DelegateDecl(string name, Expression returnType, Modifiers modifiers, params ParameterDecl[] parameters)
            : this(name, returnType, modifiers)
        {
            CreateParameters().AddRange(parameters);
        }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name, return type, modifiers, and type parameters.
        /// </summary>
        public DelegateDecl(string name, Expression returnType, Modifiers modifiers, params TypeParameter[] typeParameters)
            : this(name, returnType, modifiers)
        {
            CreateTypeParameters().AddRange(typeParameters);
        }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name and return type.
        /// </summary>
        public DelegateDecl(string name, Type returnType, Modifiers modifiers)
            : this(name, TypeRef.Create(returnType), modifiers)
        { }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name and return type.
        /// </summary>
        public DelegateDecl(string name, Type returnType)
            : this(name, TypeRef.Create(returnType), Modifiers.None)
        { }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name, return type, modifiers, and parameters.
        /// </summary>
        public DelegateDecl(string name, Type returnType, Modifiers modifiers, params ParameterDecl[] parameters)
            : this(name, TypeRef.Create(returnType), modifiers, parameters)
        { }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name, return type, modifiers, and type parameters.
        /// </summary>
        public DelegateDecl(string name, Type returnType, Modifiers modifiers, params TypeParameter[] typeParameters)
            : this(name, TypeRef.Create(returnType), modifiers, typeParameters)
        { }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name and return type.
        /// </summary>
        public DelegateDecl(string name, ITypeDecl returnType, Modifiers modifiers)
            : this(name, returnType.CreateRef(), modifiers)
        { }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name and return type.
        /// </summary>
        public DelegateDecl(string name, ITypeDecl returnType)
            : this(name, returnType.CreateRef(), Modifiers.None)
        { }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name, return type, modifiers, and parameters.
        /// </summary>
        public DelegateDecl(string name, ITypeDecl returnType, Modifiers modifiers, params ParameterDecl[] parameters)
            : this(name, returnType.CreateRef(), modifiers, parameters)
        { }

        /// <summary>
        /// Create a <see cref="DelegateDecl"/> with the specified name, return type, modifiers, and type parameters.
        /// </summary>
        public DelegateDecl(string name, ITypeDecl returnType, Modifiers modifiers, params TypeParameter[] typeParameters)
            : this(name, returnType.CreateRef(), modifiers, typeParameters)
        { }

        #endregion

        #region /* PROPERTIES */

        /// <summary>
        /// The return type of the delegate (never null - will be type 'void' instead).
        /// </summary>
        public Expression ReturnType
        {
            get { return (_returnType ?? TypeRef.VoidRef); }
            set { SetField(ref _returnType, value, true); }
        }

        /// <summary>
        /// The list of <see cref="ParameterDecl"/>s.
        /// </summary>
        public ChildList<ParameterDecl> Parameters
        {
            get { return _parameters; }
        }

        /// <summary>
        /// True if there are any parameters.
        /// </summary>
        public bool HasParameters
        {
            get { return (_parameters != null && _parameters.Count > 0); }
        }

        /// <summary>
        /// The number of parameters.
        /// </summary>
        public int ParameterCount
        {
            get { return (_parameters != null ? _parameters.Count : 0); }
        }

        /// <summary>
        /// True if the type is a delegate type.
        /// </summary>
        public override bool IsDelegateType
        {
            get { return true; }
        }

        /// <summary>
        /// The keyword associated with the <see cref="Statement"/>.
        /// </summary>
        public override string Keyword
        {
            get { return ParseToken; }
        }

        #endregion

        #region /* METHODS */

        /// <summary>
        /// Create the list of <see cref="ParameterDecl"/>s, or return the existing list.
        /// </summary>
        public ChildList<ParameterDecl> CreateParameters()
        {
            if (_parameters == null)
                _parameters = new ChildList<ParameterDecl>(this);
            return _parameters;
        }

        /// <summary>
        /// Add one or more <see cref="ParameterDecl"/>s.
        /// </summary>
        public void AddParameter(ParameterDecl parameterDecl)
        {
            CreateParameters().Add(parameterDecl);
        }

        /// <summary>
        /// Get the parameters of this delegate type.
        /// </summary>
        public override ICollection GetDelegateParameters()
        {
            // Return an empty list instead of null if we have no parameters - this is used elsewhere
            // to distinguish between zero parameters and no parameters available.
            return (_parameters ?? new List<ParameterDecl>());
        }

        /// <summary>
        /// Get the return type of this delegate type.
        /// </summary>
        public override TypeRefBase GetDelegateReturnType()
        {
            return (_returnType != null ? _returnType.EvaluateType() : null);
        }

        /// <summary>
        /// Get the base type.
        /// </summary>
        public override TypeRef GetBaseType()
        {
            return TypeRef.MulticastDelegateRef;
        }

        /// <summary>
        /// Get the non-static constructor with the specified parameters.
        /// </summary>
        public override ConstructorRef GetConstructor(params TypeRefBase[] parameterTypes)
        {
            ConstructorDecl found = GetMethod<ConstructorDecl>(Name, parameterTypes);
            if (found != null)
                return (ConstructorRef)found.CreateRef();
            return null;  // Don't look in base types for DelegateDecls
        }

        /// <summary>
        /// The name of the parameter of the constructor of the delegate that accepts a delegate type.
        /// </summary>
        public const string DelegateConstructorParameterName = "target";

        /// <summary>
        /// Get all non-static constructors for this type.
        /// </summary>
        public override NamedCodeObjectGroup GetConstructors(bool currentPartOnly)
        {
            // Find the constructor (ignore 'currentPartOnly', since delegates have no bodies)
            TypeRef delegateTypeRef = CreateRef();
            ConstructorRef constructorRef = GetConstructor(delegateTypeRef);
            return new NamedCodeObjectGroup(constructorRef != null ? constructorRef.Reference : null);
        }

        /// <summary>
        /// Create (or re-create) the compiler-generated invoke methods and constructor.
        /// This method should be called whenever the parameters of the delegate are set or changed.
        /// </summary>
        public void GenerateMethods()
        {
            // Remove any existing methods before generating them - since the Body is compiler-generated just
            // to hold these methods, we can just re-create it.
            Body = new Block { IsGenerated = true };

            // The Invoke method has the same parameters as the delegate, and the same return type
            MethodDecl invokeDecl = new MethodDecl("Invoke", (Expression)_returnType.Clone(), Modifiers.Public) { IsGenerated = true };
            invokeDecl.Parameters = (_parameters != null ? ChildListHelpers.Clone(_parameters, invokeDecl) : null);
            Add(invokeDecl);

            // The BeginInvoke method has the same parameters as the delegate, plus 2 extra ones, and a return type of IAsyncResult
            MethodDecl beginInvokeDecl = new MethodDecl("BeginInvoke", (TypeRef)TypeRef.IAsyncResultRef.Clone(), Modifiers.Public) { IsGenerated = true };
            ChildList<ParameterDecl> parameters = (_parameters != null ? ChildListHelpers.Clone(_parameters, beginInvokeDecl) : new ChildList<ParameterDecl>(beginInvokeDecl));
            parameters.Add(new ParameterDecl("callback", (TypeRef)TypeRef.AsyncCallbackRef.Clone()));
            parameters.Add(new ParameterDecl("object", (TypeRef)TypeRef.ObjectRef.Clone()));
            beginInvokeDecl.Parameters = parameters;
            Add(beginInvokeDecl);

            // The EndInvoke method has any 'ref' or 'out' parameters of the delegate, plus 1 extra one, and the same return type
            MethodDecl endInvokeDecl = new MethodDecl("EndInvoke", (Expression)_returnType.Clone(), Modifiers.Public) { IsGenerated = true };
            parameters = new ChildList<ParameterDecl>(endInvokeDecl);
            if (_parameters != null)
            {
                foreach (ParameterDecl parameterDecl in _parameters)
                {
                    if (parameterDecl.IsRef || parameterDecl.IsOut)
                        parameters.Add((ParameterDecl)parameterDecl.Clone());
                }
            }
            parameters.Add(new ParameterDecl("result", (TypeRef)TypeRef.IAsyncResultRef.Clone()));
            endInvokeDecl.Parameters = parameters;
            Add(endInvokeDecl);

            // Delegates have a constructor that takes an object and an IntPtr that is used internally by the compiler during
            // code generation.  We have to create a dummy constructor that will allow a MethodRef to be passed to it, in order
            // to make the C# syntax work when resolving.
            TypeRef delegateTypeRef = CreateRef();
            ConstructorDecl constructor = new ConstructorDecl(new[] { new ParameterDecl(DelegateConstructorParameterName, delegateTypeRef) }) { IsGenerated = true };
            Add(constructor);
        }

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

        #endregion

        #region /* PARSING */

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

        /// <summary>
        /// The token used to parse the start of the parameters.
        /// </summary>
        public const string ParseTokenStart = ParameterDecl.ParseTokenStart;

        /// <summary>
        /// The token used to parse the end of the parameters.
        /// </summary>
        public const string ParseTokenEnd = ParameterDecl.ParseTokenEnd;

        internal static void AddParsePoints()
        {
            // Delegates are only valid with a Namespace or TypeDecl parent, but we'll allow any IBlock so that we can
            // properly parse them if they accidentally end up at the wrong level (only to flag them as errors).
            // This also allows for them to be embedded in a DocCode object.
            // Use a parse-priority of 0 (AnonymousMethod uses 100)
            Parser.AddParsePoint(ParseToken, Parse, typeof(IBlock));
        }

        /// <summary>
        /// Parse a <see cref="DelegateDecl"/>.
        /// </summary>
        public static DelegateDecl Parse(Parser parser, CodeObject parent, ParseFlags flags)
        {
            return new DelegateDecl(parser, parent);
        }

        protected DelegateDecl(Parser parser, CodeObject parent)
            : base(parser, parent)
        {
            MoveComments(parser.LastToken);                                         // Get any comments before 'class'
            parser.NextToken();                                                     // Move past 'delegate'
            SetField(ref _returnType, Expression.Parse(parser, this, true), true);  // Parse the return type

            ParseNameTypeParameters(parser);  // Parse the name and any optional type parameters

            // Parse the parameter declarations
            bool isEndFirstOnLine;
            _parameters = ParameterDecl.ParseList(parser, this, ParseTokenStart, ParseTokenEnd, false, out isEndFirstOnLine);
            IsEndFirstOnLine = isEndFirstOnLine;

            ParseModifiersAndAnnotations(parser);  // Parse any attributes and/or modifiers
            ParseConstraintClauses(parser);  // Parse any constraint clauses
            ParseTerminator(parser);
            GenerateMethods();  // Generate invoke methods and constructor
        }

        #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.Phase3)) == 0)
            {
                if (_returnType != null)
                    _returnType = (Expression)_returnType.Resolve(ResolveCategory.Type, flags);
                ChildListHelpers.Resolve(_parameters, ResolveCategory.CodeObject, flags);
            }
            return base.Resolve(ResolveCategory.CodeObject, flags);
        }

        /// <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)
        {
            ChildListHelpers.ResolveRef(_typeParameters, name, resolver);
            if (resolver.HasCompleteMatch) return;  // Abort if we found a match
            ChildListHelpers.ResolveRef(_parameters, name, resolver);
            if (resolver.HasCompleteMatch) return;  // Abort if we found a match
            TypeRef baseRef = GetBaseType();
            if (baseRef != null)
            {
                TypeRefBase typeRefBase = baseRef.EvaluateType();
                if (typeRefBase != null)
                {
                    typeRefBase.ResolveRef(name, resolver);
                    if (resolver.HasCompleteMatch) return;  // Abort if we found a match
                }
            }
            if (_parent != null)
                _parent.ResolveRefUp(name, resolver);
        }

        /// <summary>
        /// Similar to <see cref="ResolveRefUp"/>, but skips trying to resolve the symbol in the body or parameters of a
        /// method (used for resolving parameter types).
        /// </summary>
        public override void ResolveRefUpSkipMethodBody(string name, Resolver resolver)
        {
            ChildListHelpers.ResolveRef(_typeParameters, name, resolver);
            if (resolver.HasCompleteMatch) return;  // Abort if we found a match
            TypeRef baseRef = GetBaseType();
            if (baseRef != null)
            {
                TypeRefBase typeRefBase = baseRef.EvaluateType();
                if (typeRefBase != null)
                {
                    typeRefBase.ResolveRef(name, resolver);
                    if (resolver.HasCompleteMatch) return;  // Abort if we found a match
                }
            }
            if (_parent != null)
                _parent.ResolveRefUp(name, resolver);
        }

        /// <summary>
        /// Returns true if the code object is an <see cref="UnresolvedRef"/> or has any <see cref="UnresolvedRef"/> children.
        /// </summary>
        public override bool HasUnresolvedRef()
        {
            if (ChildListHelpers.HasUnresolvedRef(_parameters))
                return true;
            if (_returnType != null && _returnType.HasUnresolvedRef())
                return true;
            return base.HasUnresolvedRef();
        }

        #endregion

        #region /* FORMATTING */

        /// <summary>
        /// True if the <see cref="Statement"/> has parens around its argument.
        /// </summary>
        public override bool HasArgumentParens
        {
            get { return true; }
        }

        /// <summary>
        /// True if the <see cref="Statement"/> has a terminator character by default.
        /// </summary>
        public override bool HasTerminatorDefault
        {
            get { return true; }
        }

        /// <summary>
        /// Determine a default of 1 or 2 newlines when adding items to a <see cref="Block"/>.
        /// </summary>
        public override int DefaultNewLines(CodeObject previous)
        {
            // Default to a preceeding blank line if the object has first-on-line annotations, or if
            // it's not another delegate declaration.
            if (HasFirstOnLineAnnotations || !(previous is DelegateDecl))
                return 2;
            return 1;
        }

        /// <summary>
        /// Determines if the code object only requires a single line for display.
        /// </summary>
        public override bool IsSingleLine
        {
            get
            {
                return (base.IsSingleLine && (_returnType == null || (!_returnType.IsFirstOnLine && _returnType.IsSingleLine))
                    && (_parameters == null || _parameters.Count == 0 || (!_parameters[0].IsFirstOnLine && _parameters.IsSingleLine)));
            }
            set
            {
                base.IsSingleLine = value;
                if (value)
                {
                    if (_returnType != null)
                    {
                        _returnType.IsFirstOnLine = false;
                        _returnType.IsSingleLine = true;
                    }
                    if (_parameters != null && _parameters.Count > 0)
                    {
                        _parameters[0].IsFirstOnLine = false;
                        _parameters.IsSingleLine = true;
                    }
                }
            }
        }

        #endregion

        #region /* RENDERING */

        protected override void AsTextStatement(CodeWriter writer, RenderFlags flags)
        {
            RenderFlags passFlags = (flags & RenderFlags.PassMask);
            UpdateLineCol(writer, flags);
            writer.Write(ParseToken);
            _returnType.AsText(writer, passFlags | RenderFlags.IsPrefix | RenderFlags.PrefixSpace);
            base.AsTextArgument(writer, flags);
        }

        protected override void AsTextArgumentPrefix(CodeWriter writer, RenderFlags flags)
        { }

        protected override void AsTextArgument(CodeWriter writer, RenderFlags flags)
        {
            RenderFlags passFlags = (flags & RenderFlags.PassMask);
            AsTextInfixComments(writer, 0, flags);
            writer.WriteList(_parameters, passFlags, this);
            if (IsEndFirstOnLine)
                writer.WriteLine();
        }

        #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).

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