Ejemplo n.º 1
0
        internal void Remove(Type sourceType, Type destinationType)
        {
            var key = new TypeTuple(sourceType, destinationType);

            Remove(key);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Item1 - True, if isExpression returns true
        /// Item2 - If Item1 is true, it contains the type of the alias that is defined in the isExpression 
        /// </summary>
        private Tuple<bool, AbstractType> evalIsExpression_EvalSpecToken(IsExpression isExpression, AbstractType typeToCheck, bool DoAliasHandling = false)
        {
            bool r = false;
            AbstractType res = null;

            switch (isExpression.TypeSpecializationToken)
            {
                /*
                 * To handle semantic tokens like "return" or "super" it's just needed to
                 * look into the current resolver context -
                 * then, we'll be able to gather either the parent method or the currently scoped class definition.
                 */
                case DTokens.Struct:
                case DTokens.Union:
                case DTokens.Class:
                case DTokens.Interface:
                    if (r = typeToCheck is UserDefinedType &&
                        ((TemplateIntermediateType)typeToCheck).Definition.ClassType == isExpression.TypeSpecializationToken)
                        res = typeToCheck;
                    break;

                case DTokens.Enum:
                    if (!(typeToCheck is EnumType))
                        break;
                    {
                        var tr = (UserDefinedType)typeToCheck;
                        r = true;
                        res = tr.Base;
                    }
                    break;

                case DTokens.Function:
                case DTokens.Delegate:
                    if (typeToCheck is DelegateType)
                    {
                        var isFun = false;
                        var dgr = (DelegateType)typeToCheck;
                        if (!dgr.IsFunctionLiteral)
                            r = isExpression.TypeSpecializationToken == (
                                (isFun = ((DelegateDeclaration)dgr.DeclarationOrExpressionBase).IsFunction) ? DTokens.Function : DTokens.Delegate);
                        // Must be a delegate otherwise
                        else
                            isFun = !(r = isExpression.TypeSpecializationToken == DTokens.Delegate);

                        if (r)
                        {
                            //TODO
                            if (isFun)
                            {
                                // TypeTuple of the function parameter types. For C- and D-style variadic functions, only the non-variadic parameters are included.
                                // For typesafe variadic functions, the ... is ignored.
                            }
                            else
                            {
                                // the function type of the delegate
                            }
                        }
                    }
                    else // Normal functions are also accepted as delegates
                    {
                        r = isExpression.TypeSpecializationToken == DTokens.Delegate &&
                            typeToCheck is MemberSymbol &&
                            ((DSymbol)typeToCheck).Definition is DMethod;

                        //TODO: Alias handling, same as couple of lines above
                    }
                    break;

                case DTokens.Super: //TODO: Test this
                    var dc = DResolver.SearchClassLikeAt(ctxt.ScopedBlock, isExpression.Location) as DClassLike;

                    if (dc != null)
                    {
                        var udt = DResolver.ResolveBaseClasses(new ClassType(dc, dc, null), ctxt, true) as ClassType;

                        if (r = udt.Base != null && ResultComparer.IsEqual(typeToCheck, udt.Base))
                        {
                            var l = new List<AbstractType>();
                            if (udt.Base != null)
                                l.Add(udt.Base);
                            if (udt.BaseInterfaces != null && udt.BaseInterfaces.Length != 0)
                                l.AddRange(udt.BaseInterfaces);

                            res = new TypeTuple(isExpression, l);
                        }
                    }
                    break;

                case DTokens.Const:
                case DTokens.Immutable:
                case DTokens.InOut: // TODO?
                case DTokens.Shared:
                    if (r = typeToCheck.Modifier == isExpression.TypeSpecializationToken)
                        res = typeToCheck;
                    break;

                case DTokens.Return: // TODO: Test
                    IStatement _u = null;
                    var dm = DResolver.SearchBlockAt(ctxt.ScopedBlock, isExpression.Location, out _u) as DMethod;

                    if (dm != null)
                    {
                        var retType_ = TypeDeclarationResolver.GetMethodReturnType(dm, ctxt);

                        if (r = retType_ != null && ResultComparer.IsEqual(typeToCheck, retType_))
                            res = retType_;
                    }
                    break;
            }

            return new Tuple<bool, AbstractType>(r, res);
        }
Ejemplo n.º 3
0
        public Expression <Func <TSource, TDestination> > CreateProjectionExpression <TDestination>()
        {
            var tuple = new TypeTuple(typeof(TSource), typeof(TDestination));

            return((Expression <Func <TSource, TDestination> >) this.Config.CreateMapExpression(tuple, MapType.Projection));
        }
Ejemplo n.º 4
0
        public void CompileProjection(Type sourceType, Type destinationType)
        {
            var tuple = new TypeTuple(sourceType, destinationType);

            _projectionDict[tuple] = CreateProjectionCallExpression(tuple);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Item1 - True, if isExpression returns true
        /// Item2 - If Item1 is true, it contains the type of the alias that is defined in the isExpression
        /// </summary>
        private Tuple <bool, AbstractType> evalIsExpression_EvalSpecToken(IsExpression isExpression, AbstractType typeToCheck, bool DoAliasHandling = false)
        {
            bool         r   = false;
            AbstractType res = null;

            switch (isExpression.TypeSpecializationToken)
            {
            /*
             * To handle semantic tokens like "return" or "super" it's just needed to
             * look into the current resolver context -
             * then, we'll be able to gather either the parent method or the currently scoped class definition.
             */
            case DTokens.Struct:
            case DTokens.Union:
            case DTokens.Class:
            case DTokens.Interface:
                if (r = typeToCheck is UserDefinedType &&
                        ((TemplateIntermediateType)typeToCheck).Definition.ClassType == isExpression.TypeSpecializationToken)
                {
                    res = typeToCheck;
                }
                break;

            case DTokens.Enum:
                if (!(typeToCheck is EnumType))
                {
                    break;
                }
                {
                    var tr = (UserDefinedType)typeToCheck;
                    r   = true;
                    res = tr.Base;
                }
                break;

            case DTokens.Function:
            case DTokens.Delegate:
                if (typeToCheck is DelegateType)
                {
                    var isFun = false;
                    var dgr   = (DelegateType)typeToCheck;
                    if (!dgr.IsFunctionLiteral)
                    {
                        r = isExpression.TypeSpecializationToken == (
                            (isFun = ((DelegateDeclaration)dgr.DeclarationOrExpressionBase).IsFunction) ? DTokens.Function : DTokens.Delegate);
                    }
                    // Must be a delegate otherwise
                    else
                    {
                        isFun = !(r = isExpression.TypeSpecializationToken == DTokens.Delegate);
                    }

                    if (r)
                    {
                        //TODO
                        if (isFun)
                        {
                            // TypeTuple of the function parameter types. For C- and D-style variadic functions, only the non-variadic parameters are included.
                            // For typesafe variadic functions, the ... is ignored.
                        }
                        else
                        {
                            // the function type of the delegate
                        }
                    }
                }
                else                         // Normal functions are also accepted as delegates
                {
                    r = isExpression.TypeSpecializationToken == DTokens.Delegate &&
                        typeToCheck is MemberSymbol &&
                        ((DSymbol)typeToCheck).Definition is DMethod;

                    //TODO: Alias handling, same as couple of lines above
                }
                break;

            case DTokens.Super:                     //TODO: Test this
                var dc = DResolver.SearchClassLikeAt(ctxt.ScopedBlock, isExpression.Location) as DClassLike;

                if (dc != null)
                {
                    var udt = DResolver.ResolveBaseClasses(new ClassType(dc, dc, null), ctxt, true) as ClassType;

                    if (r = udt.Base != null && ResultComparer.IsEqual(typeToCheck, udt.Base))
                    {
                        var l = new List <AbstractType>();
                        if (udt.Base != null)
                        {
                            l.Add(udt.Base);
                        }
                        if (udt.BaseInterfaces != null && udt.BaseInterfaces.Length != 0)
                        {
                            l.AddRange(udt.BaseInterfaces);
                        }

                        res = new TypeTuple(isExpression, l);
                    }
                }
                break;

            case DTokens.Const:
            case DTokens.Immutable:
            case DTokens.InOut:                     // TODO?
            case DTokens.Shared:
                if (r = typeToCheck.Modifier == isExpression.TypeSpecializationToken)
                {
                    res = typeToCheck;
                }
                break;

            case DTokens.Return:                     // TODO: Test
                IStatement _u = null;
                var        dm = DResolver.SearchBlockAt(ctxt.ScopedBlock, isExpression.Location, out _u) as DMethod;

                if (dm != null)
                {
                    var retType_ = TypeDeclarationResolver.GetMethodReturnType(dm, ctxt);

                    if (r = retType_ != null && ResultComparer.IsEqual(typeToCheck, retType_))
                    {
                        res = retType_;
                    }
                }
                break;
            }

            return(new Tuple <bool, AbstractType>(r, res));
        }
Ejemplo n.º 6
0
        private static void GenerateMappers(MapperOptions opt)
        {
            using var dynamicContext = new AssemblyResolver(Path.GetFullPath(opt.Assembly));
            var assembly = dynamicContext.Assembly;
            var config   = TypeAdapterConfig.GlobalSettings;

            config.SelfContainedCodeGeneration = true;
            config.Scan(assembly);

            foreach (var type in assembly.GetTypes())
            {
                if (!type.IsInterface)
                {
                    continue;
                }
                var attr = type.GetCustomAttribute <MapperAttribute>();
                if (attr == null)
                {
                    continue;
                }

                Console.WriteLine($"Processing: {type.FullName}");

                var definitions = new TypeDefinitions
                {
                    Implements = new[] { type },
                    Namespace  = opt.Namespace ?? type.Namespace,
                    TypeName   = attr.Name ?? GetImplName(type.Name),
                    IsInternal = attr.IsInternal
                };
                var translator = new ExpressionTranslator(definitions);
                var interfaces = type.GetAllInterfaces();
                foreach (var @interface in interfaces)
                {
                    foreach (var prop in @interface.GetProperties())
                    {
                        if (!prop.PropertyType.IsGenericType)
                        {
                            continue;
                        }
                        if (prop.PropertyType.GetGenericTypeDefinition() != typeof(Expression <>))
                        {
                            continue;
                        }
                        var propArgs = prop.PropertyType.GetGenericArguments()[0];
                        if (!propArgs.IsGenericType)
                        {
                            continue;
                        }
                        if (propArgs.GetGenericTypeDefinition() != typeof(Func <,>))
                        {
                            continue;
                        }
                        var funcArgs = propArgs.GetGenericArguments();
                        var tuple    = new TypeTuple(funcArgs[0], funcArgs[1]);
                        var expr     = config.CreateMapExpression(tuple, MapType.Projection);
                        translator.VisitLambda(expr, ExpressionTranslator.LambdaType.PublicLambda,
                                               prop.Name);
                    }
                }

                foreach (var @interface in interfaces)
                {
                    foreach (var method in @interface.GetMethods())
                    {
                        if (method.IsGenericMethod)
                        {
                            continue;
                        }
                        if (method.ReturnType == typeof(void))
                        {
                            continue;
                        }
                        var methodArgs = method.GetParameters();
                        if (methodArgs.Length < 1 || methodArgs.Length > 2)
                        {
                            continue;
                        }
                        var tuple = new TypeTuple(methodArgs[0].ParameterType, method.ReturnType);
                        var expr  = config.CreateMapExpression(tuple,
                                                               methodArgs.Length == 1 ? MapType.Map : MapType.MapToTarget);
                        translator.VisitLambda(expr, ExpressionTranslator.LambdaType.PublicMethod,
                                               method.Name);
                    }
                }

                var code = translator.ToString();
                var path = Path.Combine(Path.GetFullPath(opt.Output), definitions.TypeName + ".g.cs");
                WriteFile(code, path);
            }
        }
Ejemplo n.º 7
0
 public MapRead mapRead(IEnumerable <IType> mapTypeArgs)
 {
     Debug.Assert(mapTypeArgs.Count() == mapType.typeParameters.Length);
     return(BasicMapRead.mapRead(mapType, TypeTuple.make(mapTypeArgs)));
 }
Ejemplo n.º 8
0
        public static BasicMapWrite makeMapWrite(
            IEnumerable <IType> mapTypeArgumentsA,
            IEnumerable <IType> argumentTypesA,
            IType resultType)
        {
            var mapTypeArguments = TypeTuple.make(mapTypeArgumentsA);
            var argumentTypes    = TypeTuple.make(argumentTypesA);

            Debug.Assert(mapTypeArguments != null);
            Debug.Assert(argumentTypes != null);
            Debug.Assert(argumentTypes.Count() > 1);
            var mapType    = argumentTypes[0] as MapType;
            var sourceType = argumentTypes.Last();

            Debug.Assert(mapType != null);
            Debug.Assert(mapType.domain.Count() == argumentTypes.Count() - 2);
            Debug.Assert(mapType.typeParameters.Count() == mapTypeArguments.Count());

            var indexString = "";

            foreach (var a in argumentTypes)
            {
                indexString += (indexString == "" ? "" : ",") + a.ToString();
            }

            var indexTypes = TypeTuple.make(argumentTypes.Skip(1).Take(argumentTypes.Count() - 2));

            BasicMapWrite result        = null;
            bool          foundInstance = instances.TryGetValue(indexString, out result);

            if (result != null)
            {
                if (!ReferenceEquals(resultType, result.resultType))
                {
                    foundInstance = false;
                }
                else
                {
                    for (int i = 0; i < argumentTypes.Count(); i++)
                    {
                        if (!ReferenceEquals(argumentTypes[i], result.argumentTypes[i]))
                        {
                            foundInstance = false;
                            break;
                        }
                    }
                }
            }

            if (!foundInstance)
            {
                result = new BasicMapWrite(mapType, indexTypes, sourceType, resultType, mapTypeArguments);
                Debug.Assert(indexString != null);
                Debug.Assert(instances != null);
                Debug.Assert(result != null);
//                instances.Add(indexString,result);
                instances[indexString] = result;
            }

            return(result);
        }
 public Function getInstance()
 {
     return(getInstance(TypeTuple.make()));
 }
        public static MapRead mu2ml(MapWrite mu)
        {
            var mlArgTypes = TypeTuple.make(mu.argumentTypes.Take(mu.argumentTypes.Count() - 1));

            return(BasicMapRead.mapRead(mu.typeArguments.Skip(1).ToArray(), mlArgTypes, mu.argumentTypes.Last()));
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            IType
                Int   = TypeSingleton.Integer,
                Bool  = TypeSingleton.Boolean,
                Str   = TypeSingleton.String,
                Func  = new TypeFunction(new TypeTuple(), TypeSingleton.Void),
                Tuple = new TypeTuple(),
                Union = new TypeUnion(),
                Void  = TypeSingleton.Void,
                Any   = TypeSingleton.Any;

            Tokenizer
                Indentation        = Tokenizers.Indentation,
                MathOperator       = Tokenizers.Predicate("&|+-".Contains),
                MathOperator2      = Tokenizers.Predicate("*/%".Contains),
                ComparisonOperator = Tokenizers.Predicate("=<>".Contains),
                PrefixOperator     = Tokenizers.Match("!"),
                String             = Tokenizers.Quote('"', '"'),
                Integer            = Tokenizers.Predicate(char.IsDigit),
                Symbol             = Tokenizers.Predicate(char.IsLetterOrDigit);

            var compiler = new CompilerHelper(Indentation, MathOperator, MathOperator2, PrefixOperator, ComparisonOperator, String, Integer, Symbol);
            Func <string, Token> GetToken = compiler.GetToken;

            var SymbolParser = Tokens(Symbol);

            Parser <TypeName> TypeName;
            Parser <IEnumerable <TypeName> >           TypeNames = null;
            Parser <(string, TypeName)>                Variable;
            Parser <IEnumerable <(string, TypeName)> > Variables;

            TypeName  = parser => new TypeName(SymbolParser.Invoke(parser), TypeNames(parser));
            TypeNames = ListOf(GetToken("{"), TypeName, GetToken(","), GetToken("}"));
            Variable  = parser => (SymbolParser.Invoke(parser), TypeName(parser));
            Variables = ListOf(GetToken("["), Variable, GetToken(","), GetToken("]"));

            var expr = new ExprBuilders(new ExprWriters());

            // Parser to Analyzer mappings
            compiler.ParserRules.SetRules(
                ParserRules.Rule(expr.CheckedCast, Prefix(GetToken("->"), TypeName), Expression),
                ParserRules.Rule(expr.Sequence, Sequence(Indentation, Expression)),
                ParserRules.Rule(expr.Function, Variables, Expression),
                ParserRules.Rule(expr.Function, ListOf(GetToken("{"), Variable, GetToken(","), GetToken("}")), Variables, Expression),
                ParserRules.Rule(expr.VariableAssign, Prefix(GetToken("let"), Suffix(SymbolParser, GetToken("="))), Expression),
                ParserRules.Rule(expr.Identity, Prefix(GetToken("("), Suffix(Expression, GetToken(")")))),
                ParserRules.Rule(expr.LiteralString, Tokens(String)),
                ParserRules.Rule(expr.LiteralInt, Tokens(Integer)),
                ParserRules.Rule(expr.LiteralBooleanTrue, GetToken("true")),
                ParserRules.Rule(expr.LiteralBooleanFalse, GetToken("false")),
                ParserRules.Rule(expr.If, Prefix(GetToken("if"), Expression), Expression, Prefix(GetToken("else"), Expression)),
                ParserRules.Rule(expr.This, GetToken("this")),
                ParserRules.Rule(expr.FunctionOperatorSingle, Tokens(PrefixOperator), Expression),
                ParserRules.Rule(expr.Variable, SymbolParser)
                );
            compiler.ParserRules.SetInfixRules(
                ParserRules.Rule(expr.ContextVariable, weight: 6, Prefix(GetToken("."), SymbolParser)),
                ParserRules.Rule(expr.FunctionSetGenerics, weight: 5, TypeNames),
                ParserRules.Rule(expr.FunctionOperator, weight: 4, Tokens(MathOperator2), WeightedExpression(4)),
                ParserRules.Rule(expr.FunctionOperator, weight: 3, Tokens(MathOperator), WeightedExpression(3)),
                ParserRules.Rule(expr.FunctionOperator, weight: 2, Tokens(ComparisonOperator), WeightedExpression(2)),
                ParserRules.Rule(expr.BooleanAnd, weight: 1, Prefix(GetToken("and"), WeightedExpression(1))),
                ParserRules.Rule(expr.BooleanOr, weight: 1, Prefix(GetToken("or"), WeightedExpression(1))),
                ParserRules.Rule(expr.FunctionCall, weight: 6, ListOf(GetToken("("), Expression, GetToken(","), GetToken(")")))
                );

            compiler.AddType("int", Int);
            compiler.AddType("bool", Bool);
            compiler.AddType("string", Str);
            compiler.AddType("fun", Func);
            compiler.AddType("tuple", Tuple);
            compiler.AddType("union", Union);
            compiler.AddType("any", Any);
            compiler.AddType("void", Void);

            // Set of core functions.
            // TODO Optimize: compiler should 'unwrap' all short functions
            compiler.AddFunction("print", VMCommand.Print, Void, Any);
            compiler.AddFunction("<", VMCommand.CompareLessThan, Bool, Int, Int);
            compiler.AddFunction("+", VMCommand.MathAddition, Int, Int, Int);
            compiler.AddFunction("-", VMCommand.MathSubstraction, Int, Int, Int);
            compiler.AddFunction("*", VMCommand.MathMultiplication, Int, Int, Int);
            compiler.AddFunction("/", VMCommand.MathDivision, Int, Int, Int);
            compiler.AddFunction("!", VMCommand.BooleanNot, Bool, Bool);
            compiler.AddFunction("==", VMCommand.EqualInt, Bool, Bool, Bool);
            compiler.AddFunction("==", VMCommand.EqualInt, Bool, Int, Int);

            try
            {
                compiler.RunFile("Example");
            }
            catch (CompilationException e)
            {
                Console.WriteLine("Compilation Error: " + e.Message);
            }
        }
Ejemplo n.º 12
0
        public LambdaExpression CreateMapExpression <TDestination>()
        {
            var tuple = new TypeTuple(typeof(TSource), typeof(TDestination));

            return(this.Config.CreateMapExpression(tuple, MapType.Map));
        }
Ejemplo n.º 13
0
        ////////////////////////////////////////////////////////////////////////////////////
        private Expression makeExpression(NAryExpr fae, bool old)
        {
            if (fae.Fun is TypeCoercion)
            {
                return(makeExpression(fae.Args[0], old));
            }
            var      arguments = new ExpressionList((from Expr e in fae.Args select makeExpression(e, old)).ToArray());
            Function function;

            if (fae.Fun is MapSelect)
            {
                var typeArguments = new IType[fae.TypeParameters.FormalTypeParams.Count];
                for (int i = 0; i < fae.TypeParameters.FormalTypeParams.Count; i++)
                {
                    typeArguments[i] = makeType(fae.TypeParameters[fae.TypeParameters.FormalTypeParams[i]]);
                }
                var argumentTypes = TypeTuple.make(from a in arguments select a.type);
                function = BasicMapRead.mapRead(
                    typeArguments,
                    argumentTypes,
                    makeType(fae.Type)
                    );
            }
            else if (fae.Fun is MapStore)
            {
                var typeArguments = new IType[fae.TypeParameters.FormalTypeParams.Count];
                for (int i = 0; i < fae.TypeParameters.FormalTypeParams.Count; i++)
                {
                    typeArguments[i] = makeType(fae.TypeParameters[fae.TypeParameters.FormalTypeParams[i]]);
                }
                function = BasicMapWrite.makeMapWrite(typeArguments, (from a in arguments select a.type).ToArray(),
                                                      makeType(fae.ShallowType));
            }
            else if (fae.Fun.FunctionName == "==" || fae.Fun.FunctionName == "!=")
            {
                if (arguments[0].type.isEquivalent(arguments[1].type))
                {
                    function = BFunction.eq(arguments[0].type);
                }
                else
                {
                    Debug.Assert(!arguments[0].type.isGround || !arguments[1].type.isGround);
                    function = BFunction.eq(arguments[0].type, arguments[1].type);
                }
                if (fae.Fun.FunctionName == "!=")
                {
                    arguments = new ExpressionList(
                        new BasicFAE(
                            function,
                            arguments
                            )
                        );
                    function = scope.getFunction("!", TypeTuple.make());
                }
            }
            else if (fae.Fun.FunctionName == "<:")
            {
                function = scope.getFunction(fae.Fun.FunctionName, TypeTuple.make(new[] { arguments[0].type }));
            }
            else if (fae.Fun.FunctionName == BFunctionTemplate.iteName)
            {
                function = scope.getFunction(fae.Fun.FunctionName, TypeTuple.make(new[] { arguments[1].type }));
            }
            else if (fae.Fun.FunctionName == @"-" && fae.Fun.ArgumentCount == 1)
            {
                arguments = new ExpressionList(new[] { new BasicLiteralExpression(IntegerValue.make(0)), arguments[0] });
                function  = scope.getFunction(@"-", TypeTuple.make());
            }
            else
            {
                var typeArguments = TypeTuple.make((fae.TypeParameters == null)
                                                ? new IType[0]
                                                : (from ftp in fae.TypeParameters.FormalTypeParams
                                                   select scope.typeFactory.makeTypeI(fae.TypeParameters[ftp], context)));
                function = scope.getFunction(fae.Fun.FunctionName, typeArguments);
            }
            var result = new BoogieFunctionApplicationExpression(fae, function, arguments);

            Debug.Assert(result.type.ToStringN() ==
                         makeType(fae.Type == null ? fae.ShallowType : fae.Type).ToStringN());
            Debug.Assert(result != null);
            foreach (var fv in result.freeVariables)
            {
                Debug.Assert(context.lookupVariableByOwnName(fv.name) == fv);
            }
            foreach (var ftv in result.freeTypeVariables)
            {
                Debug.Assert(ReferenceEquals(context.lookupTypeVariable(ftv.name), ftv));
            }

            return(result);
        }
Ejemplo n.º 14
0
 public static ValueTuple Create(TypeTuple valueType, IEnumerable <ILanguageValue> value)
 {
     return(new ValueTuple(valueType, value));
 }
Ejemplo n.º 15
0
        protected ValueTuple(TypeTuple valueType, IEnumerable <ILanguageValue> value)
        {
            ValueTupleType = valueType;

            Value.AddRange(value);
        }