Beispiel #1
0
        public void ChoiceValueCaseDifferencesContributeToAmbiguousMatchTest()
        {
            ITemplateParameter param = new TemplateParameter(
                name: "TestName",
                type: "parameter",
                datatype: "choice",
                choices: new Dictionary <string, ParameterChoice>()
            {
                { "foot", new ParameterChoice("Foo", "Foo value") },
                { "bar", new ParameterChoice("Bar", "Bar value") },
                { "Football", new ParameterChoice("Football", "Foo value") },
                { "FOOTPOUND", new ParameterChoice("Footpound", "Foo value") }
            });
            IReadOnlyList <ITemplateParameter> parametersForTemplate = new List <ITemplateParameter>()
            {
                param
            };
            ITemplateInfo templateInfo = A.Fake <ITemplateInfo>();

            A.CallTo(() => templateInfo.Parameters).Returns(new List <ITemplateParameter>()
            {
                param
            });

            string?canonical = TelemetryHelper.GetCanonicalValueForChoiceParamOrDefault(templateInfo, "TestName", "foo");

            Assert.Null(canonical);
        }
        NewProjectConfiguration CreateNewProjectConfig(string baseName, string templateId, string parameters)
        {
            FilePath solutionDirectory = Util.CreateTmpDir(baseName);

            CreateNuGetConfigFile(solutionDirectory);

            string projectName = GetProjectName(templateId);

            var config = new NewProjectConfiguration {
                CreateSolution = true,
                CreateProjectDirectoryInsideSolutionDirectory = true,
                CreateGitIgnoreFile = false,
                UseGit       = false,
                Location     = solutionDirectory,
                ProjectName  = projectName,
                SolutionName = projectName
            };

            foreach (var templateParameter in TemplateParameter.CreateParameters(parameters))
            {
                config.Parameters [templateParameter.Name] = templateParameter.Value;
            }

            Directory.CreateDirectory(config.ProjectLocation);

            return(config);
        }
Beispiel #3
0
        bool IsMoreSpecialized(ITypeDeclaration Spec, TemplateParameter t2, Dictionary <TemplateParameter, ISemantic> t1_DummyParamList)
        {
            AbstractType t1_TypeResults;

            // Make a type out of t1's specialization
            using (ctxt.Push(ctxt.ScopedBlock != null ? ctxt.ScopedBlock.Parent : null))
            {
                var dict = ctxt.CurrentContext.DeducedTemplateParameters;
                // Make the T in e.g. T[] a virtual type so T will be replaced by it
                // T** will be X** then - so a theoretically valid type instead of a template param
                var dummyType = new ClassType(new DClassLike {
                    Name = "X"
                }, null, null);
                foreach (var kv in t1_DummyParamList)
                {
                    dict[kv.Key] = new TemplateParameterSymbol(t2, dummyType);
                }

                t1_TypeResults = Resolver.TypeResolution.TypeDeclarationResolver.ResolveSingle(Spec, ctxt);
            }

            if (t1_TypeResults == null)
            {
                return(true);
            }

            // Now try to fit the virtual Type t2 into t1 - and return true if it's possible
            return(new TemplateParameterDeduction(new DeducedTypeDictionary(), ctxt).Handle(t2, t1_TypeResults));
        }
        // Note: This method explicitly filters out "type" and "language", in addition to other filtering.
        public static IEnumerable <ITemplateParameter> FilterParamsForHelp(IEnumerable <ITemplateParameter> parameterDefinitions, HashSet <string> hiddenParams, bool showImplicitlyHiddenParams = false, bool hasPostActionScriptRunner = false, HashSet <string> parametersToAlwaysShow = null)
        {
            IList <ITemplateParameter> filteredParams = parameterDefinitions
                                                        .Where(x => x.Priority != TemplateParameterPriority.Implicit &&
                                                               !hiddenParams.Contains(x.Name) &&
                                                               !string.Equals(x.Name, "type", StringComparison.OrdinalIgnoreCase) &&
                                                               !string.Equals(x.Name, "language", StringComparison.OrdinalIgnoreCase) &&
                                                               (showImplicitlyHiddenParams || x.DataType != "choice" || x.Choices.Count > 1 || (parametersToAlwaysShow?.Contains(x.Name) ?? false))).ToList(); // for filtering "tags"

            if (hasPostActionScriptRunner)
            {
                ITemplateParameter allowScriptsParam = new TemplateParameter()
                {
                    Documentation = LocalizableStrings.WhetherToAllowScriptsToRun,
                    Name          = "allow-scripts",
                    DataType      = "choice",
                    DefaultValue  = "prompt",
                    Choices       = new Dictionary <string, string>()
                    {
                        { "yes", LocalizableStrings.AllowScriptsYesChoice },
                        { "no", LocalizableStrings.AllowScriptsNoChoice },
                        { "prompt", LocalizableStrings.AllowScriptsPromptChoice }
                    }
                };

                filteredParams.Add(allowScriptsParam);
            }

            return(filteredParams);
        }
Beispiel #5
0
 public TemplateParameterSymbol(TemplateParameter tpn, ISemantic typeOrValue, ISyntaxRegion paramIdentifier = null)
     : base(tpn != null ? tpn.Representation : null, AbstractType.Get(typeOrValue), paramIdentifier)
 {
     IsKnowinglyUndetermined = TemplateInstanceHandler.IsNonFinalArgument(typeOrValue);
     this.Parameter          = tpn;
     this.ParameterValue     = typeOrValue as ISymbolValue;
 }
Beispiel #6
0
        public static AST.TemplateParameter VisitTemplateParameter(TemplateParameter param)
        {
            var _param = new AST.TemplateParameter();

            _param.Name = param.Name;
            return(_param);
        }
Beispiel #7
0
 public override void VisitTemplateParameter(TemplateParameter tp)
 {
     if (tp.NameHash == searchHash && tp.Representation == symbol)
     {
         l.Add(tp);
     }
 }
Beispiel #8
0
        static async Task CreateFromTemplateAndBuild(string basename, string templateId, string parameters, Action <Solution> preBuildChecks = null, bool checkExecutionTargets = false)
        {
            using (var ptt = new DotNetCoreProjectTemplateTest(basename, templateId)) {
                foreach (var templateParameter in TemplateParameter.CreateParameters(parameters))
                {
                    ptt.Config.Parameters [templateParameter.Name] = templateParameter.Value;
                }

                var template = await ptt.CreateAndBuild(preBuildChecks);

                CheckProjectTypeGuids(ptt.Solution, GetProjectTypeGuid(template));
                // Blacklist library projects, which don't get any execution target
                if (checkExecutionTargets)
                {
                    foreach (var p in ptt.Solution.GetAllProjects().OfType <DotNetProject> ())
                    {
                        foreach (var config in p.Configurations)
                        {
                            var targets = p.GetExecutionTargets(config.Selector)?.ToList() ?? new List <ExecutionTarget> ();
                            if (System.IO.Directory.Exists("/Applications/Safari.app"))
                            {
                                Assert.True(targets.Any(x => x.Name.Contains("Safari")), $"Configuration {config.Name} didn't contain Safari");
                            }
                            if (System.IO.Directory.Exists("/Applications/Google Chrome.app"))
                            {
                                Assert.True(targets.Any(x => x.Name.Contains("Google Chrome")), $"Configuration {config.Name} didn't contain Chrome");
                            }
                        }
                    }
                }
            }
        }
Beispiel #9
0
        public void ValidChoiceForParameterIsItsOwnCanonicalValueTest()
        {
            ITemplateParameter param = new TemplateParameter(
                name: "TestName",
                type: "parameter",
                datatype: "choice",
                choices: new Dictionary <string, ParameterChoice>()
            {
                { "foo", new ParameterChoice("Foo", "Foo value") },
                { "bar", new ParameterChoice("Bar", "Bar value") }
            });

            IReadOnlyList <ITemplateParameter> parametersForTemplate = new List <ITemplateParameter>()
            {
                param
            };
            ITemplateInfo templateInfo = A.Fake <ITemplateInfo>();

            A.CallTo(() => templateInfo.Parameters).Returns(new List <ITemplateParameter>()
            {
                param
            });

            string?canonical = TelemetryHelper.GetCanonicalValueForChoiceParamOrDefault(templateInfo, "TestName", "foo");

            Assert.Equal("foo", canonical);
        }
Beispiel #10
0
        public void ChoiceValueCaseDifferenceIsAMatchTest()
        {
            ITemplateParameter param = new TemplateParameter(
                name: "TestName",
                type: "parameter",
                datatype: "choice",
                choices: new Dictionary <string, ParameterChoice>(StringComparer.OrdinalIgnoreCase)
            {
                { "foo", new ParameterChoice("Foo", "Foo value") },
                { "bar", new ParameterChoice("Bar", "Bar value") }
            });
            IReadOnlyList <ITemplateParameter> parametersForTemplate = new List <ITemplateParameter>()
            {
                param
            };
            ITemplateInfo templateInfo = A.Fake <ITemplateInfo>();

            A.CallTo(() => templateInfo.Parameters).Returns(new List <ITemplateParameter>()
            {
                param
            });

            string?canonical = TelemetryHelper.GetCanonicalValueForChoiceParamOrDefault(templateInfo, "TestName", "FOO");

            Assert.Equal("FOO", canonical);
        }
Beispiel #11
0
        internal static bool IsSame(TemplateParameter derivedParam, TemplateParameter baseParam, EntityInstance baseTemplate)
        {
            if (baseParam.Constraint.Modifier.HasConst != derivedParam.Constraint.Modifier.HasConst)
            {
                return(false);
            }

            {
                HashSet <IEntityInstance> derived_bases = derivedParam.Constraint.BaseOfNames
                                                          .Select(it => it.Evaluation.Components).ToHashSet(EntityInstance.ComparerI);
                IEnumerable <IEntityInstance> base_bases = baseParam.Constraint.BaseOfNames
                                                           .Select(it => it.Evaluation.Components.TranslateThrough(baseTemplate)).ToArray();
                if (!derived_bases.SetEquals(base_bases))
                {
                    return(false);
                }
            }

            {
                HashSet <IEntityInstance> derived_inherits = derivedParam.Constraint.InheritsNames
                                                             .Select(it => it.Evaluation.Components).ToHashSet(EntityInstance.ComparerI);
                IEnumerable <IEntityInstance> base_inherits = baseParam.Constraint.InheritsNames
                                                              .Select(it => it.Evaluation.Components.TranslateThrough(baseTemplate)).ToArray();

                if (!derived_inherits.SetEquals(base_inherits))
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #12
0
 static bool CheckAndDeduceTypeAgainstTplParameter(TemplateParameter handledParameter,
                                                   ISemantic argumentToCheck,
                                                   DeducedTypeDictionary deducedTypes,
                                                   ResolutionContext ctxt)
 {
     return(new Templates.TemplateParameterDeduction(deducedTypes, ctxt).Handle(handledParameter, argumentToCheck));
 }
        bool IsMoreSpecialized(TemplateParameter t1, TemplateParameter t2, Dictionary <TemplateParameter, ISemantic> t1_dummyParameterList)
        {
            if (t1 is TemplateTypeParameter && t2 is TemplateTypeParameter &&
                !IsMoreSpecialized((TemplateTypeParameter)t1, (TemplateTypeParameter)t2, t1_dummyParameterList))
            {
                return(false);
            }
            else if (t1 is TemplateValueParameter && t2 is TemplateValueParameter &&
                     !IsMoreSpecialized((TemplateValueParameter)t1, (TemplateValueParameter)t2))
            {
                return(false);
            }
            else if (t1 is TemplateAliasParameter && t2 is TemplateAliasParameter &&
                     !IsMoreSpecialized((TemplateAliasParameter)t1, (TemplateAliasParameter)t2, t1_dummyParameterList))
            {
                return(false);
            }
            else if (t1 is TemplateThisParameter && t2 is TemplateThisParameter && !
                     IsMoreSpecialized(((TemplateThisParameter)t1).FollowParameter, ((TemplateThisParameter)t2).FollowParameter, t1_dummyParameterList))
            {
                return(false);
            }
            else if (t1 is TemplateAliasParameter && t2 is TemplateTypeParameter)
            {
                return(true);
            }

            return(false);
        }
Beispiel #14
0
 public override void VisitTemplateParameter(TemplateParameter tp)
 {
     if (PushSelectionRange(tp))
     {
         base.VisitTemplateParameter(tp);
     }
 }
 public T Find <T>(TemplateParameter parameter, T defaultValue)
 {
     if (!_parameters.ContainsKey(parameter.ToString()))
     {
         return(defaultValue);
     }
     return((T)_parameters[parameter.ToString()]);
 }
Beispiel #16
0
		public bool ContainsTemplateParameter(TemplateParameter p)
		{
			if(TemplateParameters != null)
				for(int i = 0; i < TemplateParameters.Length; i++)
					if(TemplateParameters[i] == p)
						return true;
			return false;
		}
Beispiel #17
0
 public MockTemplateInfo WithParameters(params string[] parameters)
 {
     foreach (var param in parameters)
     {
         _parameters[param] = new TemplateParameter(param, "parameter", "string", priority: TemplateParameterPriority.Optional);
     }
     return(this);
 }
Beispiel #18
0
        public int Create(TemplateParameter parameters)
        {
            var viewModel   = MapFromClientParameters(parameters);
            var entity      = viewModel.MapTo <Template>();
            var savedEntity = MasterFileService.Add(entity);

            return(savedEntity.Id);
        }
Beispiel #19
0
        protected virtual TemplateParameter GetParatmers()
        {
            var parameters = new TemplateParameter();

            parameters.Add(RepositoryBuilderConstants.EntityName, GetEntityName);
            parameters.Add(RepositoryBuilderConstants.GetByUIdStp, $"[dbo].[{Entity.Entity.Name}_GetFullByUId]");
            return(parameters);
        }
Beispiel #20
0
        public void IndexOfFindsTemplate()
        {
            var collection = new TemplateParameterCollection();
            var param      = new TemplateParameter("test", "string", "");

            collection.Add(param);
            Assert.AreEqual(0, collection.IndexOf(param));
        }
Beispiel #21
0
        private TemplateParameter TemplateParameters()
        {
            var parameters = new TemplateParameter();

            parameters.Add(SqlConstants.TableName, Name);
            parameters.Add(SqlConstants.StpPropertyNames, string.Join("," + Environment.NewLine, GetSqlParameterNames()) + ",");
            return(parameters);
        }
Beispiel #22
0
        public override Maybe <Link> ToHomeAccount()
        {
            var username = HttpContext?.User?.Identity?.Name;

            return
                (username == null?ToAction <HomeController>(x => x.AccountHome(TemplateParameter.Create <string>()))
                     : ToAction <HomeController>(x => x.AccountHome(username)));
        }
Beispiel #23
0
        /// <summary>
        /// Returns false if the item has already been set before and if the already set item is not equal to 'r'.
        /// Inserts 'r' into the target dictionary and returns true otherwise.
        /// </summary>
        bool Set(TemplateParameter p, ISemantic r, int nameHash)
        {
            if (p == null)
            {
                if (nameHash != 0 && TargetDictionary.ExpectedParameters != null)
                {
                    foreach (var tpar in TargetDictionary.ExpectedParameters)
                    {
                        if (tpar.NameHash == nameHash)
                        {
                            p = tpar;
                            break;
                        }
                    }
                }
            }

            if (p == null)
            {
                ctxt.LogError(null, "no fitting template parameter found!");
                return(false);
            }

            // void call(T)(T t) {}
            // call(myA) -- T is *not* myA but A, so only assign myA's type to T.
            if (p is TemplateTypeParameter)
            {
                var newR = Resolver.TypeResolution.DResolver.StripMemberSymbols(AbstractType.Get(r));
                if (newR != null)
                {
                    r = newR;
                }
            }

            TemplateParameterSymbol rl;

            if (!TargetDictionary.TryGetValue(p, out rl) || rl == null)
            {
                TargetDictionary[p] = new TemplateParameterSymbol(p, r);
                return(true);
            }
            else
            {
                if (ResultComparer.IsEqual(rl.Base, r))
                {
                    TargetDictionary[p] = new TemplateParameterSymbol(p, r);
                    return(true);
                }
                else if (rl == null)
                {
                    TargetDictionary[p] = new TemplateParameterSymbol(p, r);
                }

                // Error: Ambiguous assignment

                return(false);
            }
        }
Beispiel #24
0
        private TemplateParameter GetChangeTrackingParametersParameters(string description, string columnName, string tableName)
        {
            var parameters = new TemplateParameter();

            parameters.Add(SqlConstants.TableName, tableName);
            parameters.Add(SqlConstants.Description, description);
            parameters.Add(SqlConstants.Columnname, columnName);
            return(parameters);
        }
Beispiel #25
0
        private TemplateParameter GetParameters(bool isDelete)
        {
            var parameters = new TemplateParameter();

            parameters.Add(SqlConstants.TableName, Name);
            parameters.Add(SqlConstants.StpPropertyNames, string.Join("," + Environment.NewLine, GetSqlParameterNames()));
            parameters.Add(SqlConstants.StpDeletetedPropertyNames, string.Join("," + Environment.NewLine, GetDeletedParameterNames(isDelete)));
            return(parameters);
        }
Beispiel #26
0
        private TemplateParameter GetHistoryParameters()
        {
            var parameters = new TemplateParameter();

            parameters.Add(SqlConstants.TableName, $"{Name}_historie");
            parameters.Add(SqlConstants.Description, string.IsNullOrEmpty(Entity.Description) ? Name : Entity.Description);
            parameters.Add(SqlConstants.DescriptionColumns, GetHistoryColumnDescriptions);
            return(parameters);
        }
Beispiel #27
0
        protected virtual TemplateParameter GetParameters()
        {
            var parameters = new TemplateParameter();

            parameters.Add(SqlConstants.TableName, _entity.Name);
            parameters.Add(SqlConstants.Description, GetColumnDescription());
            parameters.Add(SqlConstants.Columnname, _property.SelectSqlParameterNaam);
            return(parameters);
        }
        private bool evalIsExpression_WithAliases(IsExpression isExpression, AbstractType typeToCheck)
        {
            /*
             * Note: It's needed to let the abstract ast scanner also scan through IsExpressions etc.
             * in order to find aliases and/or specified template parameters!
             */

            var expectedTemplateParams = new TemplateParameter[isExpression.TemplateParameterList.Length + 1];

            expectedTemplateParams [0] = isExpression.ArtificialFirstSpecParam;
            if (expectedTemplateParams.Length > 1)
            {
                isExpression.TemplateParameterList.CopyTo(expectedTemplateParams, 1);
            }

            var tpl_params = new DeducedTypeDictionary(expectedTemplateParams);


            var  tpd     = new TemplateParameterDeduction(tpl_params, ctxt);
            bool retTrue = false;

            if (isExpression.EqualityTest)             // 6.
            {
                // a)
                if (isExpression.TypeSpecialization != null)
                {
                    tpd.EnforceTypeEqualityWhenDeducing = true;
                    retTrue = tpd.Handle(isExpression.ArtificialFirstSpecParam, typeToCheck);
                    tpd.EnforceTypeEqualityWhenDeducing = false;
                }
                else                 // b)
                {
                    var r = evalIsExpression_EvalSpecToken(isExpression, typeToCheck, true);
                    retTrue = r.Item1;
                    tpl_params[isExpression.TypeAliasIdentifierHash] = new TemplateParameterSymbol(null, r.Item2);
                }
            }
            else             // 5.
            {
                retTrue = tpd.Handle(isExpression.ArtificialFirstSpecParam, typeToCheck);
            }

            if (retTrue && isExpression.TemplateParameterList != null)
            {
                foreach (var p in isExpression.TemplateParameterList)
                {
                    if (!tpd.Handle(p, tpl_params[p.NameHash] != null ? tpl_params[p.NameHash].Base : null))
                    {
                        return(false);
                    }
                }
            }

            //TODO: Put all tpl_params results into the resolver context or make a new scope or something!

            return(retTrue);
        }
Beispiel #29
0
        private TemplateParameter GetParameters()
        {
            var parameters = new TemplateParameter();

            parameters.Add(SqlConstants.TableName, Entity.Name);
            parameters.Add(SqlConstants.TableProperties, GetTableProperties());

            return(parameters);
        }
 public TerminatingStringTemplate(string name, IEnumerable<TemplateParameter> parameters,
     int endingValue, int offsetMod, StringComparer stringComparer)
 {
     this.offsetMod = offsetMod;;
     this.parameter = parameters.First();
     this.endingValue = BitConverter.GetBytes(endingValue).Take(parameter.LenghtInBytes).ToArray();
     this.name = name;
     this.comparer = stringComparer;
 }
Beispiel #31
0
        protected override TemplateParameter GetParameters()
        {
            var parameters = new TemplateParameter();

            parameters.Add(SqlConstants.TableName, $"{_entity.Name}_historie");
            parameters.Add(SqlConstants.Description, GetColumnDescription());
            parameters.Add(SqlConstants.Columnname, _property.SelectSqlParameterNaam);
            return(parameters);
        }
Beispiel #32
0
        public void RemoveRemovesTemplate()
        {
            var collection = new TemplateParameterCollection();
            var param      = new TemplateParameter("test", "string", "");

            collection.Add(param);
            Assert.AreEqual(1, collection.Count);
            collection.Remove(param);
            Assert.AreEqual(0, collection.Count);
        }
Beispiel #33
0
		public bool TryGetTemplateParameter(int nameHash, out TemplateParameter p)
		{
			if (TemplateParameters != null)
				for (int i = 0; i < TemplateParameters.Length; i++)
					if (TemplateParameters[i].NameHash == nameHash)
					{
						p = TemplateParameters[i];
						return true;
					}

			p = null;
			return false;
		}
		private bool evalIsExpression_WithAliases(IsExpression isExpression, AbstractType typeToCheck)
		{
			/*
			 * Note: It's needed to let the abstract ast scanner also scan through IsExpressions etc.
			 * in order to find aliases and/or specified template parameters!
			 */

			var expectedTemplateParams = new TemplateParameter[isExpression.TemplateParameterList == null  ? 1 : (isExpression.TemplateParameterList.Length + 1)];
			expectedTemplateParams [0] = isExpression.ArtificialFirstSpecParam;
			if(expectedTemplateParams.Length > 1)
				isExpression.TemplateParameterList.CopyTo (expectedTemplateParams, 1);

			var tpl_params = new DeducedTypeDictionary(expectedTemplateParams);


			var tpd = new TemplateParameterDeduction(tpl_params, ctxt);
			bool retTrue = false;

			if (isExpression.EqualityTest) // 6.
			{
				// a)
				if (isExpression.TypeSpecialization != null)
				{
					tpd.EnforceTypeEqualityWhenDeducing = true;
					retTrue = tpd.Handle(isExpression.ArtificialFirstSpecParam, typeToCheck);
					tpd.EnforceTypeEqualityWhenDeducing = false;
				}
				else // b)
				{
					var r = evalIsExpression_EvalSpecToken(isExpression, typeToCheck, true);
					retTrue = r.Item1;
					tpl_params[isExpression.ArtificialFirstSpecParam] = new TemplateParameterSymbol(isExpression.ArtificialFirstSpecParam, r.Item2);
				}
			}
			else // 5.
				retTrue = tpd.Handle(isExpression.ArtificialFirstSpecParam, typeToCheck);

			if (retTrue && isExpression.TemplateParameterList != null)
				foreach (var p in isExpression.TemplateParameterList)
					if (!tpd.Handle(p, tpl_params[p] != null ? tpl_params[p].Base : null))
						return false;

			if (retTrue)
			{
				foreach (var kv in tpl_params)
					ctxt.CurrentContext.DeducedTemplateParameters[kv.Key] = kv.Value;
			}

			return retTrue;
		}
        public bool Handle(TemplateParameter parameter, ISemantic argumentToAnalyze)
        {
            // Packages aren't allowed at all
            if (argumentToAnalyze is PackageSymbol)
                return false;

            // Module symbols can be used as alias only
            if (argumentToAnalyze is ModuleSymbol &&
                !(parameter is TemplateAliasParameter))
                return false;

            //TODO: Handle __FILE__ and __LINE__ correctly - so don't evaluate them at the template declaration but at the point of instantiation

            /*
             * Introduce previously deduced parameters into current resolution context
             * to allow value parameter to be of e.g. type T whereas T is already set somewhere before
             */
            DeducedTypeDictionary _prefLocalsBackup = null;
            if (ctxt != null && ctxt.CurrentContext != null)
            {
                _prefLocalsBackup = ctxt.CurrentContext.DeducedTemplateParameters;

                var d = new DeducedTypeDictionary();
                foreach (var kv in TargetDictionary)
                    if (kv.Value != null)
                        d[kv.Key] = kv.Value;
                ctxt.CurrentContext.DeducedTemplateParameters = d;
            }

            bool res = false;

            if (parameter is TemplateAliasParameter)
                res = Handle((TemplateAliasParameter)parameter, argumentToAnalyze);
            else if (parameter is TemplateThisParameter)
                res = Handle((TemplateThisParameter)parameter, argumentToAnalyze);
            else if (parameter is TemplateTypeParameter)
                res = Handle((TemplateTypeParameter)parameter, argumentToAnalyze);
            else if (parameter is TemplateValueParameter)
                res = Handle((TemplateValueParameter)parameter, argumentToAnalyze);
            else if (parameter is TemplateTupleParameter)
                res = Handle((TemplateTupleParameter)parameter, new[] { argumentToAnalyze });

            if (ctxt != null && ctxt.CurrentContext != null)
                ctxt.CurrentContext.DeducedTemplateParameters = _prefLocalsBackup;

            return res;
        }
		private bool evalIsExpression_WithAliases(IsExpression isExpression, AbstractType typeToCheck)
		{
			/*
			 * Note: It's needed to let the abstract ast scanner also scan through IsExpressions etc.
			 * in order to find aliases and/or specified template parameters!
			 */

			var expectedTemplateParams = new TemplateParameter[isExpression.TemplateParameterList.Length + 1];
			expectedTemplateParams [0] = isExpression.ArtificialFirstSpecParam;
			if(expectedTemplateParams.Length > 1)
				isExpression.TemplateParameterList.CopyTo (expectedTemplateParams, 1);

			var tpl_params = new DeducedTypeDictionary(expectedTemplateParams);


			var tpd = new TemplateParameterDeduction(tpl_params, ctxt);
			bool retTrue = false;

			if (isExpression.EqualityTest) // 6.
			{
				// a)
				if (isExpression.TypeSpecialization != null)
				{
					tpd.EnforceTypeEqualityWhenDeducing = true;
					retTrue = tpd.Handle(isExpression.ArtificialFirstSpecParam, typeToCheck);
					tpd.EnforceTypeEqualityWhenDeducing = false;
				}
				else // b)
				{
					var r = evalIsExpression_EvalSpecToken(isExpression, typeToCheck, true);
					retTrue = r.Item1;
					tpl_params[isExpression.TypeAliasIdentifierHash] = new TemplateParameterSymbol(null, r.Item2);
				}
			}
			else // 5.
				retTrue = tpd.Handle(isExpression.ArtificialFirstSpecParam, typeToCheck);

			if (retTrue && isExpression.TemplateParameterList != null)
				foreach (var p in isExpression.TemplateParameterList)
					if (!tpd.Handle(p, tpl_params[p.NameHash] != null ? tpl_params[p.NameHash].Base : null))
						return false;

			//TODO: Put all tpl_params results into the resolver context or make a new scope or something! 

			return retTrue;
		}
Beispiel #37
0
 protected TemplateParameter(TemplateParameter.Internal* native, bool skipVTables = false)
 {
     if (native == null)
         return;
     __Instance = new global::System.IntPtr(native);
 }
Beispiel #38
0
 private TemplateParameter(TemplateParameter.Internal native, bool skipVTables = false)
     : this(__CopyValue(native), skipVTables)
 {
     __ownsNativeInstance = true;
     NativeToManagedMap[__Instance] = this;
 }
Beispiel #39
0
 public static TemplateParameter __CreateInstance(TemplateParameter.Internal native, bool skipVTables = false)
 {
     return new TemplateParameter(native, skipVTables);
 }
Beispiel #40
0
 private static void* __CopyValue(TemplateParameter.__Internal native)
 {
     var ret = Marshal.AllocHGlobal(140);
     global::CppSharp.Parser.AST.TemplateParameter.__Internal.cctor_1(ret, new global::System.IntPtr(&native));
     return ret.ToPointer();
 }
		bool IsMoreSpecialized(TemplateParameter t1, TemplateParameter t2, Dictionary<TemplateParameter, ISemantic> t1_dummyParameterList)
		{
			if (t1 is TemplateTypeParameter && t2 is TemplateTypeParameter &&
				!IsMoreSpecialized((TemplateTypeParameter)t1, (TemplateTypeParameter)t2, t1_dummyParameterList))
				return false;
			else if (t1 is TemplateValueParameter && t2 is TemplateValueParameter &&
				!IsMoreSpecialized((TemplateValueParameter)t1, (TemplateValueParameter)t2))
				return false;
			else if (t1 is TemplateAliasParameter && t2 is TemplateAliasParameter &&
				!IsMoreSpecialized((TemplateAliasParameter)t1, (TemplateAliasParameter)t2, t1_dummyParameterList))
				return false;
			else if (t1 is TemplateThisParameter && t2 is TemplateThisParameter && !
				IsMoreSpecialized(((TemplateThisParameter)t1).FollowParameter, ((TemplateThisParameter)t2).FollowParameter, t1_dummyParameterList))
				return false;
			else if (t1 is TemplateAliasParameter && t2 is TemplateTypeParameter)
				return true;

			return false;
		}
        /// <summary>
        /// Returns false if the item has already been set before and if the already set item is not equal to 'r'.
        /// Inserts 'r' into the target dictionary and returns true otherwise.
        /// </summary>
        bool Set(TemplateParameter p, ISemantic r, int nameHash)
        {
            if (p == null) {
                if (nameHash != 0 && TargetDictionary.ExpectedParameters != null) {
                    foreach (var tpar in TargetDictionary.ExpectedParameters)
                        if (tpar.NameHash == nameHash) {
                            p = tpar;
                            break;
                        }
                }
            }

            if (p == null) {
                ctxt.LogError (null, "no fitting template parameter found!");
                return false;
            }

            // void call(T)(T t) {}
            // call(myA) -- T is *not* myA but A, so only assign myA's type to T.
            if (p is TemplateTypeParameter)
            {
                var newR = Resolver.TypeResolution.DResolver.StripMemberSymbols(AbstractType.Get(r));
                if (newR != null)
                    r = newR;
            }

            TemplateParameterSymbol rl;
            if (!TargetDictionary.TryGetValue(p, out rl) || rl == null)
            {
                TargetDictionary[p] = new TemplateParameterSymbol(p, r);
                return true;
            }
            else
            {
                if (ResultComparer.IsEqual(rl.Base, r))
                {
                    return true;
                }
                else
                {
                    // Error: Ambiguous assignment
                }

                TargetDictionary[p] = new TemplateParameterSymbol(p, r);

                return false;
            }
        }
 public static bool HasDefaultType(TemplateParameter p)
 {
     if (p is TemplateTypeParameter)
         return ((TemplateTypeParameter)p).Default != null;
     else if (p is TemplateAliasParameter)
     {
         var ap = (TemplateAliasParameter)p;
         return ap.DefaultExpression != null || ap.DefaultType != null;
     }
     else if (p is TemplateThisParameter)
         return HasDefaultType(((TemplateThisParameter)p).FollowParameter);
     else if (p is TemplateValueParameter)
         return ((TemplateValueParameter)p).DefaultExpression != null;
     return false;
 }
Beispiel #44
0
 internal TemplateParameter(TemplateParameter.Internal* native)
     : this(new global::System.IntPtr(native))
 {
 }
Beispiel #45
0
 internal TemplateParameter(TemplateParameter.Internal native)
     : this(&native)
 {
 }
        static bool CheckAndDeduceTypeAgainstTplParameter(TemplateParameter handledParameter, 
			ISemantic argumentToCheck,
			DeducedTypeDictionary deducedTypes,
			ResolutionContext ctxt)
        {
            return new Templates.TemplateParameterDeduction(deducedTypes, ctxt).Handle(handledParameter, argumentToCheck);
        }
Beispiel #47
0
 private TemplateParameter(TemplateParameter.Internal native)
     : this(__CopyValue(native))
 {
     __ownsNativeInstance = true;
     NativeToManagedMap[__Instance] = this;
 }
Beispiel #48
0
 public static TemplateParameter __CreateInstance(TemplateParameter.Internal native)
 {
     return new TemplateParameter(native);
 }
		public virtual void Visit(TemplateParameter.Node n)
		{
			VisitDNode(n);

			n.TemplateParameter.Accept(this);
		}
 public override void VisitTemplateParameter(TemplateParameter tp)
 {
     AddResult (tp, DTokens.Not);
 }
		public virtual void VisitTemplateParameter(TemplateParameter tp) {
		}
Beispiel #52
0
 public TemplateParameterSymbol(TemplateParameter tpn, ISemantic typeOrValue, ISyntaxRegion paramIdentifier = null)
     : base(tpn != null ? tpn.Representation : null, AbstractType.Get(typeOrValue), paramIdentifier)
 {
     this.Parameter = tpn;
     this.ParameterValue = typeOrValue as ISymbolValue;
 }
Beispiel #53
0
 public override void VisitTemplateParameter(TemplateParameter tp)
 {
     if (tp.NameHash == searchHash && tp.Representation == symbol)
         l.Add (tp);
 }
        bool IsMoreSpecialized(ITypeDeclaration Spec, TemplateParameter t2, Dictionary<int, ISemantic> t1_DummyParamList)
        {
            // Make a type out of t1's specialization
            var pop = ctxt.ScopedBlock != null;
            if(pop)
                ctxt.PushNewScope(ctxt.ScopedBlock.Parent as IBlockNode);
            var frame = ctxt.CurrentContext;

            // Make the T in e.g. T[] a virtual type so T will be replaced by it
            // T** will be X** then - so a theoretically valid type instead of a template param
            var dummyType = new ClassType(new DClassLike { Name = "X" }, null, null);
            foreach (var kv in t1_DummyParamList)
                frame.DeducedTemplateParameters[kv.Key] = new TemplateParameterSymbol(t2,dummyType);

            var t1_TypeResults = Resolver.TypeResolution.TypeDeclarationResolver.Resolve(Spec, ctxt);

            if(pop)
                ctxt.Pop();

            if (t1_TypeResults == null || t1_TypeResults.Length == 0)
                return true;

            // Now try to fit the virtual Type t2 into t1 - and return true if it's possible
            return new TemplateParameterDeduction(new DeducedTypeDictionary(), ctxt).Handle(t2, t1_TypeResults[0]);
        }
		bool IsMoreSpecialized(ITypeDeclaration Spec, TemplateParameter t2, Dictionary<TemplateParameter, ISemantic> t1_DummyParamList)
		{
			AbstractType t1_TypeResults;
			// Make a type out of t1's specialization
			using (ctxt.Push(ctxt.ScopedBlock != null ? ctxt.ScopedBlock.Parent : null))
			{
				var dict = ctxt.CurrentContext.DeducedTemplateParameters;
				// Make the T in e.g. T[] a virtual type so T will be replaced by it
				// T** will be X** then - so a theoretically valid type instead of a template param
				var dummyType = new ClassType(new DClassLike { Name = "X" }, null, null);
				foreach (var kv in t1_DummyParamList)
					dict[kv.Key] = new TemplateParameterSymbol(t2, dummyType);

				t1_TypeResults = Resolver.TypeResolution.TypeDeclarationResolver.ResolveSingle(Spec, ctxt);
			}
			
			if (t1_TypeResults == null)
				return true;

			// Now try to fit the virtual Type t2 into t1 - and return true if it's possible
			return new TemplateParameterDeduction(new DeducedTypeDictionary(), ctxt).Handle(t2, t1_TypeResults);
		}
        private static bool DeduceParam(ResolutionContext ctxt, 
			DSymbol overload, 
			DeducedTypeDictionary deducedTypes,
			IEnumerator<ISemantic> argEnum, 
			TemplateParameter expectedParam)
        {
            if (expectedParam is TemplateThisParameter && overload.Base != null)
            {
                var ttp = (TemplateThisParameter)expectedParam;

                // Get the type of the type of 'this' - so of the result that is the overload's base
                var t = DResolver.StripMemberSymbols(overload.Base);

                if (t == null || t.DeclarationOrExpressionBase == null)
                    return false;

                //TODO: Still not sure if it's ok to pass a type result to it
                // - looking at things like typeof(T) that shall return e.g. const(A) instead of A only.

                if (!CheckAndDeduceTypeAgainstTplParameter(ttp, t, deducedTypes, ctxt))
                    return false;

                return true;
            }

            // Used when no argument but default arg given
            bool useDefaultType = false;
            if (argEnum.MoveNext() || (useDefaultType = HasDefaultType(expectedParam)))
            {
                // On tuples, take all following arguments and pass them to the check function
                if (expectedParam is TemplateTupleParameter)
                {
                    var tupleItems = new List<ISemantic>();
                    // A tuple must at least contain one item!
                    tupleItems.Add(argEnum.Current);
                    while (argEnum.MoveNext())
                        tupleItems.Add(argEnum.Current);

                    if (!CheckAndDeduceTypeTuple((TemplateTupleParameter)expectedParam, tupleItems, deducedTypes, ctxt))
                        return false;
                }
                else if (argEnum.Current != null)
                {
                    if (!CheckAndDeduceTypeAgainstTplParameter(expectedParam, argEnum.Current, deducedTypes, ctxt))
                        return false;
                }
                else if (useDefaultType && CheckAndDeduceTypeAgainstTplParameter(expectedParam, null, deducedTypes, ctxt))
                {
                    // It's legit - just do nothing
                }
                else
                    return false;
            }
            else if(expectedParam is TemplateTupleParameter)
            {
                if(!CheckAndDeduceTypeTuple(expectedParam as TemplateTupleParameter, null, deducedTypes, ctxt))
                    return false;
            }
            // There might be too few args - but that doesn't mean that it's not correct - it's only required that all parameters got satisfied with a type
            else if (!deducedTypes.AllParamatersSatisfied)
                return false;

            return true;
        }
Beispiel #57
0
 private static TemplateParameter.Internal* __CopyValue(TemplateParameter.Internal native)
 {
     var ret = Marshal.AllocHGlobal(32);
     CppSharp.Parser.AST.TemplateParameter.Internal.cctor_1(ret, new global::System.IntPtr(&native));
     return (TemplateParameter.Internal*) ret;
 }
Beispiel #58
0
 internal TemplateParameter(TemplateParameter.Internal native)
     : this(__CopyValue(native))
 {
 }
Beispiel #59
0
 protected TemplateParameter(TemplateParameter.Internal* native, bool isInternalImpl = false)
 {
     __Instance = new global::System.IntPtr(native);
 }
Beispiel #60
0
 private TemplateParameter(TemplateParameter.Internal native)
     : this(__CopyValue(native))
 {
     __ownsNativeInstance = true;
 }