Пример #1
0
        protected override void Update(CommandArrayInfo info)
        {
            ResolverContextStack ctxt;
            var rr = Resolver.DResolverWrapper.ResolveHoveredCode(out ctxt);

            bool noRes = true;

            if (rr != null && rr.Length > 0)
            {
                res = rr[rr.Length - 1];

                n = DResolver.GetResultMember(res);

                if (n != null)
                {
                    noRes = false;
                    info.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.GotoDeclaration), new Action(GotoDeclaration));
                    info.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.FindReferences), new Action(FindReferences));

                    if (RenamingRefactoring.CanRename(n))
                    {
                        info.AddSeparator();
                        info.Add(IdeApp.CommandService.GetCommandInfo(EditCommands.Rename), new Action(RenameSymbol));
                    }
                }
            }

            if(noRes)
                info.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.ImportSymbol), new Action(ImportSymbol));

            info.Add(IdeApp.CommandService.GetCommandInfo(Commands.OpenDDocumentation), new Action(OpenDDoc));
        }
		public string GenTooltipSignature(AbstractType t, bool templateParamCompletion = false, int currentMethodParam = -1)
		{
			var ds = t as DSymbol;
			if (ds != null)
			{
				if (currentMethodParam >= 0 && !templateParamCompletion && ds.Definition is DVariable && ds.Base != null)
					return GenTooltipSignature(ds.Base, false, currentMethodParam);

				var aliasedSymbol = ds.Tag<TypeDeclarationResolver.AliasTag>(TypeDeclarationResolver.AliasTag.Id);
				return GenTooltipSignature(aliasedSymbol == null || currentMethodParam >= 0 ? ds.Definition : aliasedSymbol.aliasDefinition, templateParamCompletion, currentMethodParam, DTypeToTypeDeclVisitor.GenerateTypeDecl(ds.Base), new DeducedTypeDictionary(ds));
			}

			if (t is PackageSymbol)
			{
				var pack = (t as PackageSymbol).Package;
				return "<i>(Package)</i> " + pack.ToString();
			}

			if (t is DelegateType)
			{
				var sb = new StringBuilder();
				GenDelegateSignature(t as DelegateType, sb, templateParamCompletion, currentMethodParam);
				return sb.ToString();
			}

			return DCodeToMarkup(t != null ? t.ToCode(true) : "null");
		}
Пример #3
0
		public static string GenerateCode(AbstractType t, bool pretty = false)
		{
			var vis = new DTypeToCodeVisitor(pretty);

			vis.AcceptType(t);

			return vis.sb.ToString();
		}
Пример #4
0
        public static string GenerateCode(AbstractType t)
        {
            var vis = new DTypeToCodeVisitor();

            vis.AcceptType(t);

            return vis.sb.ToString();
        }
Пример #5
0
		public ObjectCacheNode(string n, AbstractType t, ulong address) {
			if(string.IsNullOrEmpty(n))
				throw new ArgumentNullException("name","Child name must not be empty!");
			if(t == null)
				throw new ArgumentNullException("t","Abstract type of '"+n+"' must not be null!");

			Name = n;
			NodeType = t;
			this.address = address;
		}
		public ObjectCacheNode(string n, AbstractType t, string exp) {
			if(string.IsNullOrEmpty(n))
				throw new ArgumentNullException("name","Child name must not be empty!");
			if(t == null)
				throw new ArgumentNullException("t","Abstract type of '"+n+"' must not be null!");
			if(string.IsNullOrEmpty(exp))
				throw new ArgumentNullException("exp","Address expression must not be empty!");

			Name = n;
			NodeType = t;
			addressExpression = exp;
		}
Пример #7
0
			public DNode GenerateRepresentativeNode(AbstractType t, ResolutionContext ctxt)
			{
				if (NodeGetter != null)
					return NodeGetter(t, ctxt);

				return new DVariable()
				{
					Attributes = !RequireThis ? StaticAttributeList : null,
					Name = Name,
					Description = Description,
					Type = GetPropertyType(t, ctxt)
				};
			}
Пример #8
0
		//TODO: Für semantisches Highlighting den TypeRefFinder benutzen und einfach pauschal alle Ids entsprechend highlighten
		public static TooltipInformation Create(AbstractType t, ColorScheme st, bool templateParamCompletion = false, int currentMethodParam = -1)
		{
			var markupGen = new TooltipMarkupGen (st);

			var tti = new TooltipInformation { 
				SignatureMarkup = markupGen.GenTooltipSignature (t, templateParamCompletion, currentMethodParam)
			};

			var ds = t as DSymbol;
			DNode n;
			if (ds != null && (n = ds.Definition) != null)
				CreateTooltipBody (markupGen, n, tti);

			return tti;
		}
Пример #9
0
        protected DSymbol(DNode Node, AbstractType BaseType, IEnumerable <TemplateParameterSymbol> deducedTypes, ISyntaxRegion td)
            : base(BaseType, td)
        {
            if (deducedTypes != null)
            {
                this.DeducedTypes = new ReadOnlyCollection <TemplateParameterSymbol>(deducedTypes.ToList());
            }

            if (Node == null)
            {
                throw new ArgumentNullException("Node");
            }

            this.definition = new WeakReference(Node);
            NameHash        = Node.NameHash;
        }
Пример #10
0
        public string GenTooltipSignature(AbstractType t, bool templateParamCompletion = false, int currentMethodParam = -1)
        {
            var ds = t as DSymbol;
            if (ds != null)
            {
                var aliasedSymbol = ds.Tag as D_Parser.Resolver.TypeResolution.TypeDeclarationResolver.AliasTag;
                return GenTooltipSignature(aliasedSymbol == null ? ds.Definition : aliasedSymbol.aliasDefinition, templateParamCompletion, currentMethodParam, DTypeToTypeDeclVisitor.GenerateTypeDecl(ds.Base), ds.DeducedTypes != null ? new DeducedTypeDictionary(ds) : null);
            }

            if (t is PackageSymbol) {
                var pack = (t as PackageSymbol).Package;
                return "<i>(Package)</i> "+pack.ToString();
            }

            return DCodeToMarkup (t != null ? t.ToCode () : "null");
        }
		void GenUfcsAndStaticProperties(AbstractType t)
		{
			if (t.NonStaticAccess && CompletionOptions.Instance.ShowUFCSItems)
				CodeCompletion.DoTimeoutableCompletionTask(null, ctxt, () =>
					{
						try
						{
							foreach (var ufcsItem in UFCSResolver.TryResolveUFCS(t, 0, ed.CaretLocation, ctxt))
								CompletionDataGenerator.Add((ufcsItem as DSymbol).Definition);
						}
						catch(Exception ex)
						{
							Logger.LogWarn("Error during ufcs completion resolution", ex);
						}
					});
			StaticProperties.ListProperties(CompletionDataGenerator, ctxt, MemberFilter, t, t.NonStaticAccess);
		}
Пример #12
0
        public DelegateType(AbstractType ReturnType, DelegateDeclaration Declaration, IEnumerable <AbstractType> Parameters = null) : base(ReturnType, Declaration)
        {
            this.IsFunction = Declaration.IsFunction;
            if (ReturnType != null)
            {
                ReturnType.NonStaticAccess = true;
            }

            if (Parameters is AbstractType[])
            {
                this.Parameters = (AbstractType[])Parameters;
            }
            else if (Parameters != null)
            {
                this.Parameters = Parameters.ToArray();
            }
        }
Пример #13
0
        public DelegateType(AbstractType ReturnType, FunctionLiteral Literal, IEnumerable <AbstractType> Parameters)
            : base(ReturnType, Literal)
        {
            this.IsFunction = Literal.LiteralToken == DTokens.Function;
            if (ReturnType != null)
            {
                ReturnType.NonStaticAccess = true;
            }

            if (Parameters is AbstractType[])
            {
                this.Parameters = (AbstractType[])Parameters;
            }
            else if (Parameters != null)
            {
                this.Parameters = Parameters.ToArray();
            }
        }
Пример #14
0
        public static TooltipInformation Generate(AbstractType t, int currentParameter = -1, bool isInTemplateArgInsight = false)
        {
            var ms = t as MemberSymbol;
            if (ms != null)
            {
                if (ms.Definition is DVariable)
                {
                    var bt = DResolver.StripAliasSymbol(ms.Base);
                    if (bt is DelegateType)
                        return TooltipInfoGenerator.Generate(bt as DelegateType, currentParameter);
                }
                else if (ms.Definition is DMethod)
                    return TooltipInfoGenerator.Generate(ms.Definition as DMethod, isInTemplateArgInsight, currentParameter);
            }
            else if (t is TemplateIntermediateType)
                return Generate(t as TemplateIntermediateType, currentParameter);

            return new TooltipInformation();
        }
Пример #15
0
        /// <summary>
        /// returns float/double/creal when cfloat/cdouble/creal are given
        /// </summary>
        /// <returns>The reflect non complex type.</returns>
        /// <param name="t">T.</param>
        /// <param name="ctxt">Ctxt.</param>
        static ITypeDeclaration help_ReflectNonComplexType(AbstractType t, ResolutionContext ctxt)
        {
            var pt = t as PrimitiveType;

            if (pt != null)
            {
                switch (pt.TypeToken)
                {
                case DTokens.Cfloat:
                    return(new DTokenDeclaration(DTokens.Float));

                case DTokens.Cdouble:
                    return(new DTokenDeclaration(DTokens.Double));

                case DTokens.Creal:
                    return(new DTokenDeclaration(DTokens.Real));
                }
            }
            return(DTypeToTypeDeclVisitor.GenerateTypeDecl(t));
        }
Пример #16
0
        static AbstractType help_ReflectResolvedNonComplexType(AbstractType t, ResolutionContext ctxt)
        {
            var pt = t as PrimitiveType;

            if (pt != null)
            {
                switch (pt.TypeToken)
                {
                case DTokens.Cfloat:
                    return(new PrimitiveType(DTokens.Float));

                case DTokens.Cdouble:
                    return(new PrimitiveType(DTokens.Double));

                case DTokens.Creal:
                    return(new PrimitiveType(DTokens.Real));
                }
            }
            return(t);
        }
Пример #17
0
		void AcceptType(AbstractType t)
		{
			if (t == null)
				return;

			if (pretty)
			{
				var aliasTag = t.Tag<TypeDeclarationResolver.AliasTag>(TypeDeclarationResolver.AliasTag.Id);
				if (aliasTag != null)
					sb.Append(aliasTag.typeBase != null ? aliasTag.typeBase.ToString() : aliasTag.aliasDefinition.ToString(false, false)).Append('=');
			}

			if (t.Modifier != 0)
				sb.Append(DTokens.GetTokenString(t.Modifier)).Append('(');

			t.Accept(this);

			if (t.Modifier != 0)
				sb.Append(')');
		}
Пример #18
0
        public static StaticProperty TryEvalPropertyType(ResolutionContext ctxt, AbstractType t, int propName, bool staticOnly = false)
        {
            GetLookedUpType(ref t);

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

            var props = Properties[PropOwnerType.Generic];
            StaticPropertyInfo prop;

            if (props.TryGetValue(propName, out prop) || (Properties.TryGetValue(GetOwnerType(t), out props) && props.TryGetValue(propName, out prop)))
            {
                var n = prop.GenerateRepresentativeNode(t);
                return(new StaticProperty(n, n.Type != null ? TypeDeclarationResolver.ResolveSingle(n.Type, ctxt) : null, prop.ValueGetter));
            }

            return(null);
        }
Пример #19
0
        public static string GetReferenceUrl(AbstractType result, ResolutionContext ctxt, CodeLocation caret)
        {
            if (result != null) {
                var n = DResolver.GetResultMember (result);

                if (n != null && n.NodeRoot is DModule) {
                    if (IsPhobosModule (n.NodeRoot as DModule)) {
                        var phobos_url = "phobos/" + (n.NodeRoot as DModule).ModuleName.Replace ('.', '_') + ".html";

                        if (!(n is DModule))
                            phobos_url += "#" + n.Name;

                        return phobos_url;
                    }
                } else if (result is PrimitiveType || result is DelegateType || result is AssocArrayType) {

                    if (result.DeclarationOrExpressionBase is ITypeDeclaration)
                        return GetRefUrlFor ((ITypeDeclaration)result.DeclarationOrExpressionBase);
                    else if (result.DeclarationOrExpressionBase is IExpression)
                        return GetRefUrlFor ((IExpression)result.DeclarationOrExpressionBase);
                }
            }

            if (ctxt.ScopedStatement != null) {
                return GetRefUrlFor (ctxt.ScopedStatement, caret);
            } else if (ctxt.ScopedBlock is DClassLike) {
                var dc = ctxt.ScopedBlock as DClassLike;

                if (dc.ClassType == DTokens.Class)
                    return "class.html";
                else if (dc.ClassType == DTokens.Interface)
                    return "interface.html";
                else if (dc.ClassType == DTokens.Struct || dc.ClassType == DTokens.Union)
                    return "struct.html";
                else if (dc.ClassType == DTokens.Template)
                    return "template.html";
            } else if (ctxt.ScopedBlock is DEnum)
                return "enum.html";

            return null;
        }
Пример #20
0
        static void GetLookedUpType(ref AbstractType t)
        {
            while (t is AliasedType || t is PointerType)
            {
                t = (t as DerivedDataType).Base;
            }

            var tps = t as TemplateParameterSymbol;

            if (tps != null && tps.Base == null &&
                (tps.Parameter is TemplateThisParameter ? (tps.Parameter as TemplateThisParameter).FollowParameter : tps.Parameter) is TemplateTupleParameter)
            {
                return;
            }
            else
            {
                t = DResolver.StripMemberSymbols(t);
            }

            while (t is AliasedType || t is PointerType)
            {
                t = (t as DerivedDataType).Base;
            }
        }
Пример #21
0
 public PointerType(AbstractType Base, ISyntaxRegion td)
     : base(Base, td)
 {
 }
Пример #22
0
        public DSymbol(DNode Node, AbstractType BaseType, IEnumerable<TemplateParameterSymbol> deducedTypes, ISyntaxRegion td)
            : base(BaseType, td)
        {
            if(deducedTypes!=null)
                this.DeducedTypes = new ReadOnlyCollection<TemplateParameterSymbol>(deducedTypes.ToArray());

            if (Node == null)
                throw new ArgumentNullException ("Node");

            this.definition = new WeakReference(Node);
            NameHash = Node.NameHash;
        }
Пример #23
0
        public MemberSymbol(DNode member, AbstractType memberType, ISyntaxRegion td,
			ReadOnlyCollection<TemplateParameterSymbol> deducedTypes = null)
            : base(member, memberType, deducedTypes, td)
        {
        }
Пример #24
0
 public AssocArrayType(AbstractType ValueType, AbstractType KeyType, ISyntaxRegion td)
     : base(ValueType, td)
 {
     this.KeyType = KeyType;
 }
Пример #25
0
        public DelegateType(AbstractType ReturnType, FunctionLiteral Literal, IEnumerable<AbstractType> Parameters)
            : base(ReturnType, Literal)
        {
            this.IsFunction = Literal.LiteralToken == DTokens.Function;

            if (Parameters is AbstractType[])
                this.Parameters = (AbstractType[])Parameters;
            else if (Parameters != null)
                this.Parameters = Parameters.ToArray();
        }
Пример #26
0
 protected UserDefinedType(DNode Node, AbstractType baseType, ReadOnlyCollection <TemplateParameterSymbol> deducedTypes, ISyntaxRegion td) : base(Node, baseType, deducedTypes, td)
 {
 }
Пример #27
0
 public StaticProperty(DNode n, AbstractType bt, StaticProperties.ValueGetterHandler valueGetter) : base(n, bt, null)
 {
     this.n           = n;
     this.ValueGetter = valueGetter;
 }
Пример #28
0
        public TemplateIntermediateType(DClassLike dc, ISyntaxRegion td, 
			AbstractType baseType = null, InterfaceType[] baseInterfaces = null,
			ReadOnlyCollection<TemplateParameterSymbol> deducedTypes = null)
            : base(dc, baseType, deducedTypes, td)
        {
            this.BaseInterfaces = baseInterfaces;
        }
Пример #29
0
        AbstractType Type(char type = '\0')
        {
            if(type == '\0')
                type = (char)r.Read();
            switch(type)
            {
                case 'O':
                    var t = Type();
                    t.Modifier = DTokens.Shared;
                    return t;
                case 'x':
                    t = Type();
                    t.Modifier = DTokens.Const;
                    return t;
                case 'y':
                    t = Type();
                    t.Modifier = DTokens.Immutable;
                    return t;
                case 'N':
                    switch(r.Read())
                    {
                        case 'g':
                            t = Type();
                            t.Modifier = DTokens.InOut;
                            return t;
                        case 'e': // TypeNewArray ?
                            Type();
                            return null;
                    }
                    break;
                case 'A':
                    return new ArrayType(Type());
                case 'G':
                    var len = (int)Number();
                    return new ArrayType(Type(), len);
                case 'H':
                    var keyType = Type();
                    t = Type();
                    return new AssocArrayType(t, keyType);
                case 'P':
                    return new PointerType(Type());
                case 'F':
                case 'U':
                case 'W':
                case 'V':
                case 'R':
                    AbstractType ret;
                    List<DAttribute> attrs;
                    Dictionary<INode,AbstractType> pars;
                    Function(out ret, out attrs, out pars, type);

                    var dm = new DMethod(){ Parameters = pars.Keys.ToList(), Attributes = attrs };
                    return new MemberSymbol(dm, ret, null);
                case 'C':
                case 'S':
                case 'E':
                case 'T':
                case 'I':
                return TypeDeclarationResolver.ResolveSingle (QualifiedName (), ctxt);
                /*
                    return new MemberSymbol(null,null, QualifiedName());
                case 'C':
                    return new ClassType(new DClassLike(DTokens.Class), QualifiedName(), null);
                case 'S':
                    return new StructType(new DClassLike(DTokens.Struct), QualifiedName());
                case 'E':
                    return new EnumType(new DEnum(), null, QualifiedName());
                case 'T':
                    return new AliasedType(null, null, QualifiedName());
                */case 'D':
                    Function(out ret, out attrs, out pars, type);
                    var dgArgs = new List<AbstractType>();

                    foreach(var kv in pars)
                        dgArgs.Add(new MemberSymbol(kv.Key as DNode, kv.Value, null));

                    return new DelegateType(ret,new DelegateDeclaration{ Parameters = pars.Keys.ToList() }, dgArgs);
                case 'v': return new PrimitiveType(DTokens.Void);
                case 'g': return new PrimitiveType(DTokens.Byte);
                case 'h': return new PrimitiveType(DTokens.Ubyte);
                case 's': return new PrimitiveType(DTokens.Short);
                case 't': return new PrimitiveType(DTokens.Ushort);
                case 'i': return new PrimitiveType(DTokens.Int);
                case 'k': return new PrimitiveType(DTokens.Uint);
                case 'l': return new PrimitiveType(DTokens.Long);
                case 'm': return new PrimitiveType(DTokens.Ulong);
                case 'f': return new PrimitiveType(DTokens.Float);
                case 'd': return new PrimitiveType(DTokens.Double);
                case 'e': return new PrimitiveType(DTokens.Real);
                case 'o': return new PrimitiveType(DTokens.Ifloat);
                case 'p': return new PrimitiveType(DTokens.Idouble);
                case 'j': return new PrimitiveType(DTokens.Ireal);
                case 'q': return new PrimitiveType(DTokens.Cfloat);
                case 'r': return new PrimitiveType(DTokens.Cdouble);
                case 'c': return new PrimitiveType(DTokens.Creal);
                case 'b': return new PrimitiveType(DTokens.Bool);
                case 'a': return new PrimitiveType(DTokens.Char);
                case 'u': return new PrimitiveType(DTokens.Wchar);
                case 'w': return new PrimitiveType(DTokens.Dchar);
                case 'n': return null;

                case 'B':
                    len = (int)Number();
                    var items = new AbstractType[len];
                    var c = (char)r.Read();
                    for (int i = 0; i < len; i++)
                    {
                        Argument(ref c, out items[i]);
                    }

                    return new DTuple(items);
            }

            return null;
        }
Пример #30
0
 public ITypeDeclaration GetPropertyType(AbstractType t)
 {
     return(OverrideType ?? (TypeGetter != null && t != null ? TypeGetter(t) : null));
 }
Пример #31
0
 public static void ListProperties(ICompletionDataGenerator gen, MemberFilter vis, AbstractType t, bool isVariableInstance)
 {
     foreach (var n in ListProperties(t, !isVariableInstance))
     {
         if (AbstractVisitor.CanAddMemberOfType(vis, n))
         {
             gen.Add(n);
         }
     }
 }
Пример #32
0
 static ITypeDeclaration help_ReflectType(AbstractType t)
 {
     return(t.TypeDeclarationOf);
 }
Пример #33
0
 public ITypeDeclaration GetPropertyType(AbstractType t, ResolutionContext ctxt)
 {
     return(OverrideType ?? (TypeGetter != null && t != null ? TypeGetter(t, ctxt) : null));
 }
Пример #34
0
        static StaticProperties()
        {
            var props = new Dictionary <int, StaticPropertyInfo>();

            Properties[PropOwnerType.Generic] = props;

            props.AddProp(new StaticPropertyInfo("init", "A type's or variable's static initializer expression")
            {
                TypeGetter = help_ReflectType, ResolvedBaseTypeGetter = help_ReflectResolvedType
            });
            props.AddProp(new StaticPropertyInfo("sizeof", "Size of a type or variable in bytes", DTokens.Uint));             // Do not define it as size_t due to unnecessary recursive definition as typeof(int.sizeof)
            props.AddProp(new StaticPropertyInfo("alignof", "Variable offset", DTokens.Uint)
            {
                RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("mangleof", "String representing the ‘mangled’ representation of the type", "string"));
            props.AddProp(new StaticPropertyInfo("stringof", "String representing the source representation of the type", "string")
            {
                ValueGetter = (vp, v) => {
                    var t = AbstractType.Get(v);
                    if (t == null)
                    {
                        return(new NullValue());
                    }
                    return(new ArrayValue(Evaluation.GetStringType(vp.ResolutionContext), (t is DSymbol) ? DNode.GetNodePath((t as DSymbol).Definition, true) : t.ToCode()));
                }
            });



            props = new Dictionary <int, StaticPropertyInfo>();
            Properties[PropOwnerType.Integral] = props;

            props.AddProp(new StaticPropertyInfo("max", "Maximum value")
            {
                TypeGetter = help_ReflectType, ResolvedBaseTypeGetter = help_ReflectResolvedType
            });
            props.AddProp(new StaticPropertyInfo("min", "Minimum value")
            {
                TypeGetter = help_ReflectType, ResolvedBaseTypeGetter = help_ReflectResolvedType
            });



            props = new Dictionary <int, StaticPropertyInfo>();
            Properties[PropOwnerType.FloatingPoint] = props;

            props.AddProp(new StaticPropertyInfo("infinity", "Infinity value")
            {
                TypeGetter = help_ReflectType, ResolvedBaseTypeGetter = help_ReflectResolvedType
            });
            props.AddProp(new StaticPropertyInfo("nan", "Not-a-Number value")
            {
                TypeGetter = help_ReflectType, ResolvedBaseTypeGetter = help_ReflectResolvedType
            });
            props.AddProp(new StaticPropertyInfo("dig", "Number of decimal digits of precision", DTokens.Int));
            props.AddProp(new StaticPropertyInfo("epsilon", "Smallest increment to the value 1")
            {
                TypeGetter = help_ReflectType, ResolvedBaseTypeGetter = help_ReflectResolvedType
            });
            props.AddProp(new StaticPropertyInfo("mant_dig", "Number of bits in mantissa", DTokens.Int));
            props.AddProp(new StaticPropertyInfo("max_10_exp", "Maximum int value such that 10^max_10_exp is representable", DTokens.Int));
            props.AddProp(new StaticPropertyInfo("max_exp", "Maximum int value such that 2^max_exp-1 is representable", DTokens.Int));
            props.AddProp(new StaticPropertyInfo("min_10_exp", "Minimum int value such that 10^max_10_exp is representable", DTokens.Int));
            props.AddProp(new StaticPropertyInfo("min_exp", "Minimum int value such that 2^max_exp-1 is representable", DTokens.Int));
            props.AddProp(new StaticPropertyInfo("min_normal", "Number of decimal digits of precision", DTokens.Int));
            props.AddProp(new StaticPropertyInfo("re", "Real part")
            {
                TypeGetter = help_ReflectNonComplexType, ResolvedBaseTypeGetter = help_ReflectResolvedNonComplexType, RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("im", "Imaginary part")
            {
                TypeGetter = help_ReflectNonComplexType, ResolvedBaseTypeGetter = help_ReflectResolvedNonComplexType, RequireThis = true
            });



            props = new Dictionary <int, StaticPropertyInfo>();
            Properties[PropOwnerType.Array] = props;

            props.AddProp(new StaticPropertyInfo("length", "Array length", DTokens.Int)
            {
                RequireThis = true,
                ValueGetter =
                    (vp, v) => {
                    var av = v as ArrayValue;
                    return(new PrimitiveValue(DTokens.Int, av.Elements != null ? av.Elements.Length : 0, null, 0m));
                }
            });

            props.AddProp(new StaticPropertyInfo("dup", "Create a dynamic array of the same size and copy the contents of the array into it.")
            {
                TypeGetter = help_ReflectType, ResolvedBaseTypeGetter = help_ReflectResolvedType, RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("idup", "D2.0 only! Creates immutable copy of the array")
            {
                TypeGetter = (t, ctxt) => new MemberFunctionAttributeDecl(DTokens.Immutable)
                {
                    InnerType = help_ReflectType(t, ctxt)
                }, RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("reverse", "Reverses in place the order of the elements in the array. Returns the array.")
            {
                TypeGetter = help_ReflectType, ResolvedBaseTypeGetter = help_ReflectResolvedType, RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("sort", "Sorts in place the order of the elements in the array. Returns the array.")
            {
                TypeGetter = help_ReflectType, ResolvedBaseTypeGetter = help_ReflectResolvedType, RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("ptr", "Returns pointer to the array")
            {
                ResolvedBaseTypeGetter = (t, ctxt) => new PointerType((t as DerivedDataType).Base, t.DeclarationOrExpressionBase),
                TypeGetter             = (t, ctxt) => new PointerDecl(DTypeToTypeDeclVisitor.GenerateTypeDecl((t as DerivedDataType).Base)),
                RequireThis            = true
            });



            props = new Dictionary <int, StaticPropertyInfo>(props);            // Copy from arrays' properties!
            Properties[PropOwnerType.AssocArray] = props;

            props.AddProp(new StaticPropertyInfo("length", "Returns number of values in the associative array. Unlike for dynamic arrays, it is read-only.", "size_t")
            {
                RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("keys", "Returns dynamic array, the elements of which are the keys in the associative array.")
            {
                TypeGetter = (t, ctxt) => new ArrayDecl {
                    ValueType = DTypeToTypeDeclVisitor.GenerateTypeDecl((t as AssocArrayType).KeyType)
                }, RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("values", "Returns dynamic array, the elements of which are the values in the associative array.")
            {
                TypeGetter = (t, ctxt) => new ArrayDecl {
                    ValueType = DTypeToTypeDeclVisitor.GenerateTypeDecl((t as AssocArrayType).ValueType)
                }, RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("rehash", "Reorganizes the associative array in place so that lookups are more efficient. rehash is effective when, for example, the program is done loading up a symbol table and now needs fast lookups in it. Returns a reference to the reorganized array.")
            {
                TypeGetter = help_ReflectType, ResolvedBaseTypeGetter = help_ReflectResolvedType, RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("byKey", "Returns a delegate suitable for use as an Aggregate to a ForeachStatement which will iterate over the keys of the associative array.")
            {
                TypeGetter = (t, ctxt) => new DelegateDeclaration()
                {
                    ReturnType = new ArrayDecl()
                    {
                        ValueType = DTypeToTypeDeclVisitor.GenerateTypeDecl((t as AssocArrayType).KeyType)
                    }
                }, RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("byValue", "Returns a delegate suitable for use as an Aggregate to a ForeachStatement which will iterate over the values of the associative array.")
            {
                TypeGetter = (t, ctxt) => new DelegateDeclaration()
                {
                    ReturnType = new ArrayDecl()
                    {
                        ValueType = DTypeToTypeDeclVisitor.GenerateTypeDecl((t as AssocArrayType).ValueType)
                    }
                }, RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("get", null)
            {
                RequireThis = true,
                NodeGetter  = (t, ctxt) =>
                {
                    var ad        = t as AssocArrayType;
                    var valueType = DTypeToTypeDeclVisitor.GenerateTypeDecl(ad.ValueType);
                    return(new DMethod()
                    {
                        Name = "get",
                        Description = "Looks up key; if it exists returns corresponding value else evaluates and returns defaultValue.",
                        Type = valueType,
                        Parameters = new List <INode> {
                            new DVariable()
                            {
                                Name = "key",
                                Type = DTypeToTypeDeclVisitor.GenerateTypeDecl(ad.KeyType)
                            },
                            new DVariable()
                            {
                                Name = "defaultValue",
                                Type = valueType,
                                Attributes = new List <DAttribute> {
                                    new Modifier(DTokens.Lazy)
                                }
                            }
                        }
                    });
                }
            });
            props.AddProp(new StaticPropertyInfo("remove", null)
            {
                RequireThis = true,
                NodeGetter  = (t, ctxt) => new DMethod
                {
                    Name        = "remove",
                    Description = "remove(key) does nothing if the given key does not exist and returns false. If the given key does exist, it removes it from the AA and returns true.",
                    Type        = new DTokenDeclaration(DTokens.Bool),
                    Parameters  = new List <INode> {
                        new DVariable {
                            Name = "key",
                            Type = DTypeToTypeDeclVisitor.GenerateTypeDecl((t as AssocArrayType).KeyType)
                        }
                    }
                }
            });


            props = new Dictionary <int, StaticPropertyInfo>();
            Properties[PropOwnerType.TypeTuple] = props;

            props.AddProp(new StaticPropertyInfo("length", "Returns number of values in the type tuple.", "size_t")
            {
                RequireThis = true,
                ValueGetter =
                    (vp, v) => {
                    var tt = v as DTuple;
                    if (tt == null && v is TypeValue)
                    {
                        tt = (v as TypeValue).RepresentedType as DTuple;
                    }
                    return(tt != null ? new PrimitiveValue(DTokens.Int, tt.Items == null ? 0m : (decimal)tt.Items.Length, null, 0m) : null);
                }
            });



            props = new Dictionary <int, StaticPropertyInfo>();
            Properties[PropOwnerType.Delegate] = props;


            props.AddProp(new StaticPropertyInfo("ptr", "The .ptr property of a delegate will return the frame pointer value as a void*.",
                                                 (ITypeDeclaration) new PointerDecl(new DTokenDeclaration(DTokens.Void)))
            {
                RequireThis = true
            });
            props.AddProp(new StaticPropertyInfo("funcptr", "The .funcptr property of a delegate will return the function pointer value as a function type.")
            {
                RequireThis = true
            });



            props = new Dictionary <int, StaticPropertyInfo>();
            Properties[PropOwnerType.ClassLike] = props;

            props.AddProp(new StaticPropertyInfo("classinfo", "Information about the dynamic type of the class", (ITypeDeclaration) new IdentifierDeclaration("TypeInfo_Class")
            {
                ExpressesVariableAccess = true, InnerDeclaration = new IdentifierDeclaration("object")
            })
            {
                RequireThis = true
            });

            props = new Dictionary <int, StaticPropertyInfo>();
            Properties[PropOwnerType.Struct] = props;

            props.AddProp(new StaticPropertyInfo("sizeof", "Size in bytes of struct", DTokens.Uint));
            props.AddProp(new StaticPropertyInfo("alignof", "Size boundary struct needs to be aligned on", DTokens.Uint));
            props.AddProp(new StaticPropertyInfo("tupleof", "Gets type tuple of fields")
            {
                TypeGetter = (t, ctxt) =>
                {
                    var members = GetStructMembers(t as StructType, ctxt);
                    var l       = new List <IExpression>();

                    var vis = new DTypeToTypeDeclVisitor();
                    foreach (var member in members)
                    {
                        var mt = DResolver.StripMemberSymbols(member);
                        if (mt == null)
                        {
                            l.Add(null);
                            continue;
                        }
                        var td = mt.Accept(vis);
                        if (td == null)
                        {
                            l.Add(null);
                            continue;
                        }
                        l.Add(td as IExpression ?? new TypeDeclarationExpression(td));
                    }

                    return(new TemplateInstanceExpression(new IdentifierDeclaration("Tuple"))
                    {
                        Arguments = l.ToArray()
                    });
                },

                ResolvedBaseTypeGetter = (t, ctxt) =>
                {
                    var members    = GetStructMembers(t as StructType, ctxt);
                    var tupleItems = new List <ISemantic>();

                    foreach (var member in members)
                    {
                        var mt = DResolver.StripMemberSymbols(member);
                        if (mt != null)
                        {
                            tupleItems.Add(mt);
                        }
                    }

                    return(new DTuple(t.DeclarationOrExpressionBase, tupleItems));
                }
            });
        }
Пример #35
0
        DVariable Argument(ref char c, out AbstractType parType)
        {
            bool scoped;
            if(scoped = (c == 'M'))
                c = (char)r.Read(); //TODO: Handle scoped

            var par = new DVariable{ Attributes = new List<DAttribute>() };
            if(c == 'J' || c == 'K' ||c == 'L')
            {
                switch (c) {
                case 'J':
                    par.Attributes.Add (new Modifier (DTokens.Out));
                    break;
                case 'K':
                    par.Attributes.Add (new Modifier (DTokens.Ref));
                    break;
                case 'L':
                    par.Attributes.Add (new Modifier (DTokens.Lazy));
                    break;
                }
                c = (char)r.Read();
            }

            parType = Type(c);
            par.Type = DTypeToTypeDeclVisitor.GenerateTypeDecl(parType);
            return par;
        }
Пример #36
0
        /// <summary>
        /// Checks results for implicit type convertability
        /// </summary>
        public static bool IsImplicitlyConvertible(ISemantic resultToCheck, AbstractType targetType, ResolutionContext ctxt = null)
        {
            var  resToCheck = AbstractType.Get(resultToCheck);
            bool isVariable = resToCheck is MemberSymbol;

            // Initially remove aliases from results
            var _r = DResolver.StripMemberSymbols(resToCheck);

            if (_r == null)
            {
                return(IsEqual(resToCheck, targetType));
            }
            resToCheck = _r;

            if (targetType is DSymbol)
            {
                var tpn = ((DSymbol)targetType).Definition as TemplateParameter.Node;

                if (tpn != null)
                {
                    var par = tpn.Parent as DNode;

                    if (par != null && par.TemplateParameters != null)
                    {
                        var dedParam = new DeducedTypeDictionary(par);

                        return(new TemplateParameterDeduction(dedParam, ctxt).Handle(tpn.TemplateParameter, resToCheck));
                    }
                }
            }

            _r = DResolver.StripMemberSymbols(targetType);
            if (_r == null)
            {
                return(false);
            }
            targetType = _r;

            if (resToCheck is PrimitiveType && targetType is PrimitiveType)
            {
                var sr1 = (PrimitiveType)resToCheck;
                var sr2 = (PrimitiveType)targetType;

                //if (sr1.TypeToken == sr2.TypeToken /*&& sr1.Modifier == sr2.Modifier*/)
                //	return true;

                return(IsPrimitiveTypeImplicitlyConvertible(sr1.TypeToken, sr2.TypeToken));
            }
            else if (resToCheck is UserDefinedType && targetType is UserDefinedType)
            {
                return(IsImplicitlyConvertible((UserDefinedType)resToCheck, (UserDefinedType)targetType));
            }
            else if (resToCheck is DelegateType && targetType is DelegateType)
            {
                return(IsEqual(resToCheck, targetType));                //TODO: Can non-equal delegates be converted into each other?
            }
            else if (resToCheck is ArrayType && targetType is ArrayType)
            {
                var ar1 = (ArrayType)resToCheck;
                var ar2 = (ArrayType)targetType;

                // Key as well as value types must be matching!
                var ar1_n = ar1.KeyType == null;
                var ar2_n = ar2.KeyType == null;

                if (ar1_n != ar2_n)
                {
                    return(false);
                }

                if (ar1_n || IsImplicitlyConvertible(ar1.KeyType, ar2.KeyType, ctxt))
                {
                    return(IsImplicitlyConvertible(ar1.Base, ar2.Base, ctxt));
                }
            }
            else if (resToCheck is DSymbol && targetType is DSymbol)
            {
                var r1 = resToCheck as DSymbol;
                var r2 = targetType as DSymbol;

                if (r1.Definition == r2.Definition)
                {
                    //TODO: Compare template param deductions
                    return(true);
                }
            }
            else if (resToCheck is DTuple && targetType is DTuple)
            {
                var tup1 = resToCheck as DTuple;
                var tup2 = resToCheck as DTuple;

                //TODO
                return(true);
            }

            /*else if (resultToCheck is ExpressionValueResult && targetType is ExpressionValue)
             * {
             *      return ((ExpressionValueResult)resultToCheck).Value.Equals(((ExpressionValueResult)targetType).Value);
             * }*/

            // http://dlang.org/type.html
            //TODO: Pointer to non-pointer / vice-versa checkability? -- Can it really be done implicitly?
            else if (!isVariable &&
                     resToCheck is ArrayType &&
                     targetType is PointerType && ((targetType = (targetType as PointerType).Base) is PrimitiveType) &&
                     DTokens.IsBasicType_Character((targetType as PrimitiveType).TypeToken))
            {
                return((resultToCheck as ArrayType).IsString);
            }


            return(false);
        }
Пример #37
0
 static AbstractType help_ReflectResolvedType(AbstractType t, ResolutionContext ctxt)
 {
     return(t);
 }
Пример #38
0
        /// <summary>
        /// Checks results for implicit type convertability
        /// </summary>
        public static bool IsImplicitlyConvertible(ISemantic resultToCheck, AbstractType targetType, ResolverContextStack ctxt = null)
        {
            var resToCheck = AbstractType.Get(resultToCheck);

            // Initially remove aliases from results
            var _r = DResolver.StripMemberSymbols(resToCheck);

            if (_r == null)
            {
                return(IsEqual(resToCheck, targetType));
            }
            resToCheck = _r;

            targetType = DResolver.StripAliasSymbol(targetType);

            if (targetType is DSymbol)
            {
                var tpn = ((DSymbol)targetType).Definition as TemplateParameterNode;

                if (tpn != null)
                {
                    var par = tpn.Parent as DNode;

                    if (par != null && par.TemplateParameters != null)
                    {
                        var dedParam = new DeducedTypeDictionary {
                            ParameterOwner = par
                        };
                        foreach (var tp in par.TemplateParameters)
                        {
                            dedParam[tp.Name] = null;
                        }

                        return(new TemplateParameterDeduction(dedParam, ctxt).Handle(tpn.TemplateParameter, resToCheck));
                    }
                }
            }

            _r = DResolver.StripMemberSymbols(targetType);
            if (_r == null)
            {
                return(false);
            }
            targetType = _r;

            if (resToCheck is PrimitiveType && targetType is PrimitiveType)
            {
                var sr1 = (PrimitiveType)resToCheck;
                var sr2 = (PrimitiveType)targetType;

                if (sr1.TypeToken == sr2.TypeToken && sr1.Modifier == sr2.Modifier)
                {
                    return(true);
                }

                switch (sr2.TypeToken)
                {
                case DTokens.Int:
                    return(sr1.TypeToken == DTokens.Uint);

                case DTokens.Uint:
                    return(sr1.TypeToken == DTokens.Int);
                    //TODO: Further types that can be converted into each other implicitly
                }
            }
            else if (resToCheck is UserDefinedType && targetType is UserDefinedType)
            {
                return(IsImplicitlyConvertible((UserDefinedType)resToCheck, (UserDefinedType)targetType));
            }
            else if (resToCheck is DelegateType && targetType is DelegateType)
            {
                //TODO
            }
            else if (resToCheck is ArrayType && targetType is ArrayType)
            {
                var ar1 = (ArrayType)resToCheck;
                var ar2 = (ArrayType)targetType;

                // Key as well as value types must be matching!
                var ar1_n = ar1.KeyType == null;
                var ar2_n = ar2.KeyType == null;

                if (ar1_n != ar2_n)
                {
                    return(false);
                }

                if (ar1_n || IsImplicitlyConvertible(ar1.KeyType, ar2.KeyType, ctxt))
                {
                    return(IsImplicitlyConvertible(ar1.Base, ar2.Base, ctxt));
                }
            }

            else if (resToCheck is TypeTuple && targetType is TypeTuple)
            {
                return(true);
            }
            else if (resToCheck is ExpressionTuple && targetType is ExpressionTuple)
            {
                return(true);
            }

            /*else if (resultToCheck is ExpressionValueResult && targetType is ExpressionValue)
             * {
             *      return ((ExpressionValueResult)resultToCheck).Value.Equals(((ExpressionValueResult)targetType).Value);
             * }*/

            // http://dlang.org/type.html
            //TODO: Pointer to non-pointer / vice-versa checkability? -- Can it really be done implicitly?

            return(false);
        }
Пример #39
0
 public EnumType(DEnum Enum, AbstractType BaseType, ISyntaxRegion td) : base(Enum, BaseType, null, td)
 {
 }
Пример #40
0
        public bool TryGetCachedResult(INode n, out AbstractType type, params IExpression[] templateArguments)
        {
            type = null;

            return(false);
        }
Пример #41
0
 public ArrayType(AbstractType ValueType, int ArrayLength, ISyntaxRegion td)
     : this(ValueType, td)
 {
     FixedLength = ArrayLength;
     IsStaticArray = true;
 }
Пример #42
0
 public MemberSymbol(DNode member, AbstractType memberType, ISyntaxRegion td,
                     Dictionary <string, TemplateParameterSymbol> deducedTypes)
     : base(member, memberType, deducedTypes, td)
 {
 }
Пример #43
0
        public DelegateType(AbstractType ReturnType,DelegateDeclaration Declaration, IEnumerable<AbstractType> Parameters = null)
            : base(ReturnType, Declaration)
        {
            this.IsFunction = Declaration.IsFunction;

            if (Parameters is AbstractType[])
                this.Parameters = (AbstractType[])Parameters;
            else if(Parameters!=null)
                this.Parameters = Parameters.ToArray();
        }
Пример #44
0
		public SubArrayCacheNode(string n, AbstractType t, ulong firstItemPointer, int len)
			: base(n, t, firstItemPointer)
		{
			firstItem = firstItemPointer;
			length = len;
		}
Пример #45
0
 public DerivedDataType(AbstractType Base, ISyntaxRegion td)
     : base(td)
 {
     this.Base = Base;
 }
Пример #46
0
 public MemberSymbol(DNode member, AbstractType memberType, ISyntaxRegion td,
                     ReadOnlyCollection <KeyValuePair <string, TemplateParameterSymbol> > deducedTypes = null)
     : base(member, memberType, deducedTypes, td)
 {
 }
Пример #47
0
 public EnumType(DEnum Enum, AbstractType BaseType, ISyntaxRegion td)
     : base(Enum, BaseType, null, td)
 {
 }
Пример #48
0
 public ArrayType(AbstractType ValueType, ISyntaxRegion td)
     : base(ValueType, null, td)
 {
     FixedLength = -1;
 }
Пример #49
0
        public MemberSymbol(DNode member, AbstractType memberType, ISyntaxRegion td,
			IEnumerable<TemplateParameterSymbol> deducedTypes)
            : base(member, memberType, deducedTypes, td)
        {
        }
Пример #50
0
 public ArrayType(AbstractType ValueType, int ArrayLength, ISyntaxRegion td)
     : this(ValueType, td)
 {
     FixedLength   = ArrayLength;
     IsStaticArray = ArrayLength >= 0;
 }
Пример #51
0
 public StaticProperty(DNode n, AbstractType bt, StaticProperties.ValueGetterHandler valueGetter)
     : base(n, bt, null)
 {
     this.n = n;
     this.ValueGetter = valueGetter;
 }
Пример #52
0
 public AliasedType(DVariable AliasDefinition, AbstractType Type, ISyntaxRegion td, ReadOnlyCollection <KeyValuePair <string, TemplateParameterSymbol> > deducedTypes = null)
     : base(AliasDefinition, Type, td, deducedTypes)
 {
 }
Пример #53
0
        public TemplateIntermediateType(DClassLike dc, ISyntaxRegion td, 
			AbstractType baseType, InterfaceType[] baseInterfaces,
			IEnumerable<TemplateParameterSymbol> deducedTypes)
            : this(dc,td, baseType,baseInterfaces,
			deducedTypes != null ? new ReadOnlyCollection<TemplateParameterSymbol>(deducedTypes.ToArray()) : null)
        {
        }
Пример #54
0
 public UserDefinedType(DNode Node, AbstractType baseType, ReadOnlyCollection <KeyValuePair <string, TemplateParameterSymbol> > deducedTypes, ISyntaxRegion td) : base(Node, baseType, deducedTypes, td)
 {
 }
Пример #55
0
        void Function(out AbstractType returnType,
		              out List<DAttribute> attributes,
		              out Dictionary<INode,AbstractType> parameters,
		              char callConvention = 'F')
        {
            attributes = new List<DAttribute>();

            // Create artificial extern attribute
            var conv = "D";
            switch(callConvention)
            {
                case 'U':
                    conv = "C";
                    break;
                case 'W':
                    conv = "Windows";
                    break;
                case 'V':
                    conv = "Pascal";
                    break;
                case 'R':
                    conv = "C++";
                    break;
            }
            attributes.Add(new Modifier(DTokens.Extern,conv));

            var nextChar = '\0';
            do
            {
                nextChar = (char)r.Read();

                if(nextChar == 'N')
                {
                    switch(r.Peek())
                    {
                        case 'a':
                            r.Read();
                            nextChar = (char)r.Read();
                            attributes.Add(new Modifier(DTokens.Pure));
                            continue;
                        case 'b':
                            r.Read();
                            nextChar = (char)r.Read();
                            attributes.Add(new Modifier(DTokens.Nothrow));
                            continue;
                        case 'c':
                            r.Read();
                            nextChar = (char)r.Read();
                            attributes.Add(new Modifier(DTokens.Ref));
                            continue;
                        case 'd':
                            r.Read();
                            nextChar = (char)r.Read();
                            attributes.Add(new BuiltInAtAttribute(BuiltInAtAttribute.BuiltInAttributes.Property));
                            continue;
                        case 'e':
                            r.Read();
                            nextChar = (char)r.Read();
                            attributes.Add(new BuiltInAtAttribute(BuiltInAtAttribute.BuiltInAttributes.Trusted));
                            continue;
                        case 'f':
                            r.Read();
                            nextChar = (char)r.Read();
                            attributes.Add(new BuiltInAtAttribute(BuiltInAtAttribute.BuiltInAttributes.Safe));
                            continue;
                    }
                }
            }
            while(false);

            parameters = Arguments(ref nextChar);

            if(nextChar == 'X') // variadic T t...) style
            {
                var lastParam = parameters.Keys.Last();
                lastParam.Type = new VarArgDecl(lastParam.Type);
            }
            else if(nextChar == 'Y') // variadic T t,...) style
                parameters.Add(new DVariable{ Type = new VarArgDecl() }, null);
            else if(nextChar != 'Z')
                throw new ArgumentException("Expected 'X','Y' or 'Z' at the end of a function type.");

            returnType = Type();
        }
Пример #56
0
 public DSymbol(DNode Node, AbstractType BaseType, ReadOnlyCollection <KeyValuePair <string, TemplateParameterSymbol> > deducedTypes, ISyntaxRegion td)
     : base(BaseType, td)
 {
     this.DeducedTypes = deducedTypes;
     this.Definition   = Node;
 }
Пример #57
0
 protected DerivedDataType(AbstractType Base, ISyntaxRegion td) : base(td)
 {
     this.Base = Base;
 }
Пример #58
0
 static ITypeDeclaration help_ReflectType(AbstractType t, ResolutionContext ctxt)
 {
     return(DTypeToTypeDeclVisitor.GenerateTypeDecl(t));
 }
Пример #59
0
 public ArrayAccessSymbol(PostfixExpression_Index indexExpr, AbstractType arrayValueType) :
     base(arrayValueType, indexExpr)
 {
 }
Пример #60
0
 public PointerType(AbstractType Base, ISyntaxRegion td) : base(Base, td)
 {
 }