xronos /System.Xronos/Builtins/SpecialForms.FnForm.cs

Language C# Lines 152
MD5 Hash 7ba44007aa176269a3074322ce6ead9c Estimated Cost $2,534 (why?)
Repository https://bitbucket.org/stefanrusek/xronos View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/* ****************************************************************************
 * 
 * Copyright (c) 2008 Stefan Rusek and Benjamin Pollack
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 * ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xronos.Language;
using Microsoft.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Xronos.Scripting.MetaObjects;

namespace System.Xronos.Builtins
{
	public static partial class SpecialForms
    {
        internal partial class FnForm : SpecialFormBase
        {
            class RestFunction { }

            static Dictionary<string, Type> cache = new Dictionary<string, Type>();

            protected override Expression Compile(Compiler compiler, ISequence rest, Scope scope)
            {
                var name = rest.first() as Symbol;
                if (name == null)
                    name = Symbol.Create("__UnnamedMethod");
                else
                    rest = rest.rest();

                int c = -1;

                var list = new List<LambdaExpression>();
                if (rest.first() is IPersistentVector)
                {
                    list.Add(ParseFunction(compiler, name, ref c, RT.seq(rest), scope));
                }
                else
                {
                    while (rest != null)
                    {
                        list.Add(ParseFunction(compiler, name, ref c, RT.seq(rest.first()), scope));
                        rest = rest.rest();
                    }
                }

                return GetDelegateFunction(name, list);
            }

            private Expression GetDelegateFunction(Symbol name, List<LambdaExpression> list)
            {
                var map = new List<Expression>();
                foreach (var item in list)
                {
                    var arity = item.Parameters.Count - 1;

                    while (map.Count < arity)
                        map.Add(Expression.Constant(null, typeof(FunctionMapEntry)));
                    
                    var temp = Expression.Parameter(typeof(FunctionMapEntry));
                    map.Add(Expression.Block(new[] { temp },
                        Expression.Assign(temp, Expression.New(typeof(FunctionMapEntry))),
                        Expression.Assign(Expression.Field(temp, "Arity"), Expression.Constant(arity)),
                        Expression.Assign(Expression.Field(temp, "Delegate"), item),
                        Expression.Assign(Expression.Field(temp, "IsRest"), Expression.Constant(item.Annotations().Contains<RestFunction>())),
                        temp));
                }

                return Expression.New(typeof(DelegateFunction).GetConstructors()[0], Expression.NewArrayInit(typeof(FunctionMapEntry), map));
            }

            private LambdaExpression ParseFunction(Compiler compiler, Symbol self, ref int c, ISequence cons, Scope scope)
            {
                var paramNames = (IList)cons.first();
                if (c >= paramNames.Count)
                    throw new InvalidProgramException("Functions must be written in order of increasing numbers of parameters");

                c = paramNames.Count;

                var annotations = Annotations.Empty;
                var paramExprs = new List<ParameterExpression>();

                scope = new Scope(scope);
                
                {
                    var param = Expression.Parameter(typeof(object), self.ToString());
                    paramExprs.Add(param);
                    scope[self] = param;
                }

                foreach (var item in paramNames)
                {
                    var name = (Symbol)item;

                    if (name.Namespace == null && name.Name == "&")
                    {
                        annotations = annotations.Add(new RestFunction());
                        continue;
                    }

                    var param = Expression.Parameter(annotations.Contains<RestFunction>() ? typeof(ISequence) : typeof(object), name.ToString());
                    paramExprs.Add(param);
                    scope[name] = param;
                }

                if (annotations.Contains<RestFunction>() && !paramNames[paramNames.Count - 2].Equals(Symbol.Create("&")))
                    throw new ReaderException("& cannot appear before any but the last parameter");

                var label = Expression.Label();
                var vars = new List<Expression>(from p in paramExprs select (Expression)p);
                vars.RemoveAt(0);

                scope.LoopLabel = label;
                scope.LoopVariables = vars;

                return Lambda(
                    Expression.Convert(
                        LoopForm.BuildOuterLoop(compiler, null, label, DoForm.CompileDo(compiler, null, cons.rest(), null, scope), scope),
                        typeof(object)),
                    self.ToString(), annotations, paramExprs.ToArray());
            }

            public LambdaExpression Lambda(Expression body, string name, Annotations annotations, ParameterExpression[] parameters)
            {
                return Expression.Lambda(body, name, parameters).Annotate(annotations);
            }
        }
    }
}
Back to Top