Пример #1
0
 public override string GetClepsTypeString()
 {
     return(String.Format("fn {0} ({1})",
                          ReturnType.GetClepsTypeString(),
                          String.Join(",", ParameterTypes.Select(p => p.GetClepsTypeString()))
                          ));
 }
Пример #2
0
        public MethodDeclarationSyntax Output()
        {
            TypeSyntax retType;

            if (ReturnType == null)
            {
                retType = PredefinedType(Token(SyntaxKind.VoidKeyword));
            }
            else
            {
                retType = ReturnType.GenReferenceTo();
            }

            ParameterListSyntax parameters =
                ParameterList(
                    SeparatedList(
                        ParameterTypes.Select(
                            (pt, i) => Parameter(Identifier($"arg{i}")).WithType(pt.GenReferenceTo()))));

            return
                (MethodDeclaration(retType, Name)
                 .WithModifiers(TokenList(Token(SyntaxKind.StaticKeyword)))
                 .WithParameterList(parameters)
                 .WithBody(Body));
        }
Пример #3
0
        public string AsNativeName()
        {
            var paramTypes = ParameterTypes.Select((t) => t.AsNativeName());
            var paramStr   = string.Join(",", paramTypes);

            return($"({paramStr}) => {ReturnType.AsNativeName()}");
        }
Пример #4
0
 public override AstExpression Clone()
 {
     return(CopyValuesTo(new AstFunctionTypeExpr(
                             ParameterTypes.Select(p => p.Clone()).ToList(),
                             ReturnType?.Clone(),
                             IsFatFunction,
                             Directives)));
 }
Пример #5
0
        private BlockSyntax GenBlock(bool root)
        {
            _level++;

            ScopeFrame scope = new ScopeFrame();

            _scope.Add(scope);

            if (root)
            {
                scope.Variables.AddRange(ParameterTypes.Select((p, i) => new VariableIdentifier(p, $"arg{i}")));
            }

            BlockSyntax block = Block(GenStatements());

            _scope.RemoveAt(_scope.Count - 1);
            _level--;

            return(block);

            IEnumerable <StatementSyntax> GenStatements()
            {
                int             numStatements = Options.BlockStatementCountDist.Sample(Random.Rng);
                StatementSyntax retStmt       = null;

                for (int i = 0; i < numStatements; i++)
                {
                    StatementSyntax stmt = GenStatement();
                    if (stmt is ReturnStatementSyntax)
                    {
                        retStmt = stmt;
                        break;
                    }

                    yield return(stmt);
                }

                if (root && retStmt == null)
                {
                    retStmt = GenReturn();
                }

                if (Options.EnableChecksumming)
                {
                    foreach (StatementSyntax stmt in GenChecksumming(scope.Variables, _genChecksumSiteId))
                    {
                        yield return(stmt);
                    }
                }

                if (retStmt != null)
                {
                    yield return(retStmt);
                }
            }
        }
Пример #6
0
        /// <summary>
        /// Deep clone.
        /// </summary>
        public virtual Function Clone()
        {
            var result = (Function)MemberwiseClone();

            result.ResultType     = ResultType.Clone();
            result.ParameterTypes = ParameterTypes.Select(p => p.Clone()).ToArray();
            if (InputType != null)
            {
                result.InputType = InputType.Clone();
            }
            return(result);
        }
Пример #7
0
        /// <summary>
        /// Returns the CLR <see cref="MemberInfo"/>.
        /// </summary>
        /// <returns>Returns the CLR <see cref="MemberInfo"/>.</returns>
        public override MemberInfo GetClrVersion()
        {
            InterLinqTypeSystem tsInstance = InterLinqTypeSystem.Instance;

            lock (tsInstance)
            {
                if (tsInstance.IsInterLinqMemberInfoRegistered(this))
                {
                    return(tsInstance.GetClrVersion <ConstructorInfo>(this));
                }

                Type            declaringType    = (Type)DeclaringType.GetClrVersion();
                ConstructorInfo foundConstructor = declaringType.GetConstructor(ParameterTypes.Select(p => (Type)p.GetClrVersion()).ToArray());
                tsInstance.SetClrVersion(this, foundConstructor);
                return(foundConstructor);
            }
        }
Пример #8
0
        private MethodInfo GetMethodInfo()
        {
            MethodInfo mi;

            if (GenericArguments != null && GenericArguments.Length > 0)
            {
                mi = FindGenericMethod(MethodType, MethodName,
                                       GenericArguments.Select(p => p.GetSystemType()).ToArray(),
                                       ParameterTypes.Select(p => p.GetSystemType()).ToArray());
            }
            else
            {
                mi = MethodType.GetMethod(MethodName, ParameterTypes.Select(p => p.GetSystemType()).ToArray());
            }

            if (mi == null)
            {
                throw new MissingMethodException(MethodType.FullName, MethodName);
            }
            return(mi);
        }
        /// <summary>
        /// Returns the CLR <see cref="MemberInfo"/>.
        /// </summary>
        /// <returns>Returns the CLR <see cref="MemberInfo"/>.</returns>
        public override MemberInfo GetClrVersion()
        {
            InterLinqTypeSystem tsInstance = InterLinqTypeSystem.Instance;

            lock (tsInstance)
            {
                if (tsInstance.IsInterLinqMemberInfoRegistered(this))
                {
                    return(tsInstance.GetClrVersion <ConstructorInfo>(this));
                }

#if !NETFX_CORE
                Type            declaringType    = (Type)DeclaringType.GetClrVersion();
                ConstructorInfo foundConstructor = declaringType.GetConstructor(ParameterTypes.Select(p => (Type)p.GetClrVersion()).ToArray());
#else
                Type            declaringType    = ((TypeInfo)DeclaringType.GetClrVersion()).AsType();
                ConstructorInfo foundConstructor = declaringType.GetTypeInfo().DeclaredConstructors.FirstOrDefault(x => Enumerable.SequenceEqual(x.GetParameters().Select(y => y.ParameterType), ParameterTypes.Select(p => ((TypeInfo)p.GetClrVersion()).AsType())));
#endif
                tsInstance.SetClrVersion(this, foundConstructor);
                return(foundConstructor);
            }
        }
Пример #10
0
        public override string ToString()
        {
            var owner            = (!String.IsNullOrWhiteSpace(OwnerTypeAlias) ? $"[{OwnerTypeAlias}]" : String.Empty) + OwnerType?.FoundMatchingType;
            var accessModifier   = AccessModifier != MethodAccessModifier.Unknown ? $"{AccessModifier.GetName()} " : String.Empty;
            var returnType       = ReturnType?.FoundMatchingType?.ToString() ?? ReturnType?.Name;
            var methodName       = (!String.IsNullOrWhiteSpace(MethodNameAlias) ? $"[{MethodNameAlias}]" : String.Empty) + MethodName;
            var genericArguments = GenericArguments.Any() ? $"<{string.Join(", ", GenericArguments.Select(a => a.FoundMatchingType?.ToString() ?? a.Name))}>" : null;


            var parameters = ParameterTypes.Select(p => {
                var str = $"{p.Name}";
                if (!String.IsNullOrWhiteSpace(p.GenericName) && p.GenericName != p.Name)
                {
                    str = $"[{p.GenericName}]{str}";
                }
                return(p.IsOptional ? $"{str}?" : str);
            }).ToArray();

            var parametersStr = parameters.Any() ? $"({string.Join(", ", parameters)})" : null;

            return(Regex.Replace($"{owner}:{MethodType.GetName()} {accessModifier} {returnType} {methodName}{genericArguments}{parametersStr}".Trim(), @"\s+", " "));
        }
 public override string Format()
 {
     return(Formatter.Format(ReturnType) + " *i" + IntPtr.Size + "(" + string.Join(", ", ParameterTypes.Select(Formatter.Format).ToArray()) + ")");
 }
Пример #12
0
        public void FunctionCallExpression(CParser.FunctionCallExpression FunctionCallExpression)
        {
            var Function = FunctionCallExpression.Function;

            if (Function is CParser.IdentifierExpression)
            {
                var IdentifierExpression  = Function as CParser.IdentifierExpression;
                var FunctionName          = IdentifierExpression.Identifier;
                var ParametersExpressions = FunctionCallExpression.Parameters.Expressions;

                // Special functions.
                switch (FunctionName)
                {
                // Alloca Special Function.
                case "alloca":
                {
#if true
                    // alloca requires the stack to be empty after calling it?
                    var Stack = SafeILGenerator.StackSave();
                    var AllocaAddressLocal = SafeILGenerator.DeclareLocal(typeof(void *));
                    {
                        Traverse(ParametersExpressions);
                        SafeILGenerator.StackAlloc();
                    }
                    SafeILGenerator.StoreLocal(AllocaAddressLocal);
                    SafeILGenerator.StackRestore(Stack);
                    SafeILGenerator.LoadLocal(AllocaAddressLocal);
#else
                    var AllocaLocal = SafeILGenerator.DeclareLocal(typeof(void *), "AllocaLocal");
                    Traverse(FunctionCallExpression.Parameters.Expressions);
                    //SafeILGenerator.ConvertTo(typeof(void*));
                    SafeILGenerator.StackAlloc();
                    SafeILGenerator.ConvertTo(typeof(void *));
                    SafeILGenerator.StoreLocal(AllocaLocal);
                    SafeILGenerator.LoadLocal(AllocaLocal);
                    //throw(new NotImplementedException("Currently this does not work!"));
#endif
                }
                break;

                // Normal plain function.
                default:
                {
                    var VariableReference = VariableScope.Find(IdentifierExpression.Identifier);
                    var FunctionReference = FunctionScope.Find(IdentifierExpression.Identifier);

                    if (VariableReference != null)
                    {
                        var CFunctionType  = VariableReference.CType.GetSpecifiedCType <CFunctionType>();
                        var ReturnType     = ConvertCTypeToType(CFunctionType.Return);
                        var ParameterTypes = CFunctionType.Parameters.Select(Item => ConvertCTypeToType(Item.CType)).ToArray();

                        Traverse(ParametersExpressions);
                        Traverse(IdentifierExpression);
                        SafeILGenerator.CallManagedFunction(CallingConventions.Standard, ReturnType, ParameterTypes, null);
                    }
                    else if (FunctionReference != null)
                    {
                        Type[] ParameterTypes;

                        if (FunctionReference.SafeMethodTypeInfo == null)
                        {
                            if (FunctionReference.MethodInfo.CallingConvention == CallingConventions.VarArgs)
                            {
                                ParameterTypes = FunctionCallExpression.Parameters.Expressions.Select(Expression => ConvertCTypeToType(Expression.GetCachedCType(this))).ToArray();
                            }
                            else
                            {
                                ParameterTypes = FunctionReference.MethodInfo.GetParameters().Select(Parameter => Parameter.ParameterType).ToArray();
                            }
                        }
                        else
                        {
                            ParameterTypes = FunctionReference.SafeMethodTypeInfo.Parameters;
                        }

                        if (ParameterTypes.Length != ParametersExpressions.Length)
                        {
                            throw (new Exception(String.Format(
                                                     "Function parameter count mismatch {0} != {1} calling function '{2}'",
                                                     ParameterTypes.Length, ParametersExpressions.Length, FunctionName
                                                     )));
                        }

                        ParameterTypes = ParameterTypes.Select(Item => GetRealType(Item)).ToArray();

                        for (int n = 0; n < ParametersExpressions.Length; n++)
                        {
                            var Expression      = ParametersExpressions[n];
                            var ExpressionCType = Expression.GetCachedCType(this);
                            var ExpressionType  = ConvertCTypeToType(ExpressionCType);
                            var ParameterType   = GetRealType(ParameterTypes[n]);
                            Traverse(Expression);

                            // Expected a string. Convert it!
                            if (ParameterType == typeof(string))
                            {
                                if (ExpressionType == typeof(sbyte *))
                                {
                                    SafeILGenerator.ConvertTo(typeof(sbyte *));
                                    SafeILGenerator.Call((CLibUtils.PointerToStringDelegate)CLibUtils.GetStringFromPointer);
                                }
                                else
                                {
                                    throw (new NotImplementedException(String.Format("Invalid string expression {0}", ExpressionType)));
                                }
                            }
                            else
                            {
                                SafeILGenerator.ConvertTo(ParameterType);
                            }
                        }

                        if (FunctionReference.SafeMethodTypeInfo == null && FunctionReference.MethodInfo.CallingConvention == CallingConventions.VarArgs)
                        {
                            //SafeILGenerator.LoadFunctionPointer(FunctionReference.MethodInfo, IsVirtual: false);
                            //SafeILGenerator.CallManagedFunction(CallingConventions.VarArgs, FunctionReference.MethodInfo.ReturnType, ParameterTypes, null);
                            SafeILGenerator.Call(FunctionReference.MethodInfo, FunctionReference.SafeMethodTypeInfo, ParameterTypes);
                        }
                        else
                        {
                            SafeILGenerator.Call(FunctionReference.MethodInfo, FunctionReference.SafeMethodTypeInfo);
                        }
                    }
                    else
                    {
                        throw (new Exception(String.Format("Unknown function '{0}'", IdentifierExpression.Identifier)));
                    }

                    //SafeILGenerator.__ILGenerator.Emit(OpCodes.Call
                    //throw (new NotImplementedException("Function: " + IdentifierExpression.Value));
                }
                break;
                }
            }
            else
            {
                throw (new NotImplementedException());
            }
        }
        public void Parameters_Distinctly_Decorated()
        {
            var names = ParameterTypes.Select(GetParameterDecoratedName).AssertNotNull().AssertCollectionNotEmpty().ToArray();

            names.Distinct().AssertEqual(names);
        }
Пример #14
0
 public MethodInfo ToMethod(AppDomain domain)
 {
     Type[] parameterTypes = ParameterTypes.Select(t => t.ToType(domain)).ToArray();
     return(DeclaringType.ToType(domain).GetMethod(MethodName, parameterTypes));
 }
Пример #15
0
 public override string ToString()
 {
     return(string.Format("[{0} {1} ({2})]", ReturnType.Name, Name, string.Join(", ", ParameterTypes.Select(t => t.Name).ToArray())));
 }
Пример #16
0
        public virtual string GetTranslatedParameterList()
        {
            var paramTypes = ParameterTypes.Select((t) => t.AsTranslatedName());

            return(string.Join(",", paramTypes));
        }
Пример #17
0
 public string Serialize()
 {
     return("(" + string.Join("", ParameterTypes.Select(x => x.Serialize())) + ")" + ReturnType.Serialize());
 }