PageRenderTime 83ms CodeModel.GetById 40ms app.highlight 10ms RepoModel.GetById 30ms app.codeStats 0ms

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

https://bitbucket.org/stefanrusek/xronos
C# | 151 lines | 105 code | 23 blank | 23 comment | 13 complexity | 7ba44007aa176269a3074322ce6ead9c MD5 | raw file
  1/* ****************************************************************************
  2 * 
  3 * Copyright (c) 2008 Stefan Rusek and Benjamin Pollack
  4 * 
  5 * Permission is hereby granted, free of charge, to any person obtaining a copy
  6 * of this software and associated documentation files (the "Software"), to deal
  7 * in the Software without restriction, including without limitation the rights
  8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9 * copies of the Software, and to permit persons to whom the Software is
 10 * furnished to do so, subject to the following conditions:
 11 * 
 12 * The above copyright notice and this permission notice shall be included in
 13 * all copies or substantial portions of the Software.
 14 * 
 15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 21 * THE SOFTWARE.
 22 * 
 23 * ***************************************************************************/
 24using System;
 25using System.Collections.Generic;
 26using System.Linq;
 27using System.Text;
 28using System.Xronos.Language;
 29using Microsoft.Linq.Expressions;
 30using System.Reflection;
 31using System.Reflection.Emit;
 32using System.Collections;
 33using System.Xronos.Scripting.MetaObjects;
 34
 35namespace System.Xronos.Builtins
 36{
 37	public static partial class SpecialForms
 38    {
 39        internal partial class FnForm : SpecialFormBase
 40        {
 41            class RestFunction { }
 42
 43            static Dictionary<string, Type> cache = new Dictionary<string, Type>();
 44
 45            protected override Expression Compile(Compiler compiler, ISequence rest, Scope scope)
 46            {
 47                var name = rest.first() as Symbol;
 48                if (name == null)
 49                    name = Symbol.Create("__UnnamedMethod");
 50                else
 51                    rest = rest.rest();
 52
 53                int c = -1;
 54
 55                var list = new List<LambdaExpression>();
 56                if (rest.first() is IPersistentVector)
 57                {
 58                    list.Add(ParseFunction(compiler, name, ref c, RT.seq(rest), scope));
 59                }
 60                else
 61                {
 62                    while (rest != null)
 63                    {
 64                        list.Add(ParseFunction(compiler, name, ref c, RT.seq(rest.first()), scope));
 65                        rest = rest.rest();
 66                    }
 67                }
 68
 69                return GetDelegateFunction(name, list);
 70            }
 71
 72            private Expression GetDelegateFunction(Symbol name, List<LambdaExpression> list)
 73            {
 74                var map = new List<Expression>();
 75                foreach (var item in list)
 76                {
 77                    var arity = item.Parameters.Count - 1;
 78
 79                    while (map.Count < arity)
 80                        map.Add(Expression.Constant(null, typeof(FunctionMapEntry)));
 81                    
 82                    var temp = Expression.Parameter(typeof(FunctionMapEntry));
 83                    map.Add(Expression.Block(new[] { temp },
 84                        Expression.Assign(temp, Expression.New(typeof(FunctionMapEntry))),
 85                        Expression.Assign(Expression.Field(temp, "Arity"), Expression.Constant(arity)),
 86                        Expression.Assign(Expression.Field(temp, "Delegate"), item),
 87                        Expression.Assign(Expression.Field(temp, "IsRest"), Expression.Constant(item.Annotations().Contains<RestFunction>())),
 88                        temp));
 89                }
 90
 91                return Expression.New(typeof(DelegateFunction).GetConstructors()[0], Expression.NewArrayInit(typeof(FunctionMapEntry), map));
 92            }
 93
 94            private LambdaExpression ParseFunction(Compiler compiler, Symbol self, ref int c, ISequence cons, Scope scope)
 95            {
 96                var paramNames = (IList)cons.first();
 97                if (c >= paramNames.Count)
 98                    throw new InvalidProgramException("Functions must be written in order of increasing numbers of parameters");
 99
100                c = paramNames.Count;
101
102                var annotations = Annotations.Empty;
103                var paramExprs = new List<ParameterExpression>();
104
105                scope = new Scope(scope);
106                
107                {
108                    var param = Expression.Parameter(typeof(object), self.ToString());
109                    paramExprs.Add(param);
110                    scope[self] = param;
111                }
112
113                foreach (var item in paramNames)
114                {
115                    var name = (Symbol)item;
116
117                    if (name.Namespace == null && name.Name == "&")
118                    {
119                        annotations = annotations.Add(new RestFunction());
120                        continue;
121                    }
122
123                    var param = Expression.Parameter(annotations.Contains<RestFunction>() ? typeof(ISequence) : typeof(object), name.ToString());
124                    paramExprs.Add(param);
125                    scope[name] = param;
126                }
127
128                if (annotations.Contains<RestFunction>() && !paramNames[paramNames.Count - 2].Equals(Symbol.Create("&")))
129                    throw new ReaderException("& cannot appear before any but the last parameter");
130
131                var label = Expression.Label();
132                var vars = new List<Expression>(from p in paramExprs select (Expression)p);
133                vars.RemoveAt(0);
134
135                scope.LoopLabel = label;
136                scope.LoopVariables = vars;
137
138                return Lambda(
139                    Expression.Convert(
140                        LoopForm.BuildOuterLoop(compiler, null, label, DoForm.CompileDo(compiler, null, cons.rest(), null, scope), scope),
141                        typeof(object)),
142                    self.ToString(), annotations, paramExprs.ToArray());
143            }
144
145            public LambdaExpression Lambda(Expression body, string name, Annotations annotations, ParameterExpression[] parameters)
146            {
147                return Expression.Lambda(body, name, parameters).Annotate(annotations);
148            }
149        }
150    }
151}