Ejemplo n.º 1
0
        /// <summary>
        /// Registers an expression factory. The supplied name is used in markup to represent
        /// an instance of the associated expression.
        /// </summary>
        /// <param name="name">The name of expression.</param>
        /// <param name="factory">The factory to be used to handle the supplied name.</param>
        public void RegisterExpression(string name, ExpressionFactory factory)
        {
            Debug.Assert(String.IsNullOrEmpty(name) == false);
            Debug.Assert(factory != null);
            Debug.Assert(_registeredExpressions.ContainsKey(name) == false, "An expression factory with name '" + name + "' was already registered.");

            _registeredExpressions[name] = factory;
        }
Ejemplo n.º 2
0
        public CodeGenerator() {
            varTable = new Stack<Dictionary<string, ZOperand>>();
            typeTable = new Dictionary<string, Type>();
            typeStack = new Stack<TypeGen>();
            funcStack = new Stack<CodeGen>();

            name = "ZodiacConsole";
            var exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            if (exeDir == null) return;
            var exeFilePath = Path.Combine(exeDir, name + ".exe");
            Directory.CreateDirectory(exeDir);
            ag = new AssemblyGen(name, new CompilerOptions() { OutputPath = exeFilePath });
            st = ag.StaticFactory;
            exp = ag.ExpressionFactory;
            tm = ag.TypeMapper;
        }
Ejemplo n.º 3
0
 public void ThrowNullReferenceException()
 {
     Throw(ExpressionFactory.New(typeof(NullReferenceException)));
 }
Ejemplo n.º 4
0
 public void ThrowNotSupportedException()
 {
     Throw(ExpressionFactory.New(typeof(NotSupportedException)));
 }
Ejemplo n.º 5
0
 public static BoolHandle operator !=(ArrayHandle <TKeyHandle, TValueHandle> left, ArrayHandle <TKeyHandle, TValueHandle> right)
 {
     return((BoolHandle)ExpressionFactory.Distinct(left.Expression, right.Expression));
 }
Ejemplo n.º 6
0
 public static Expression IfNullElse(this Expression expression, Expression then, Expression @else = null)
 => ExpressionFactory.IfNullElse(expression, then, @else);
Ejemplo n.º 7
0
 public static LambdaExpression Concat(this LambdaExpression expr, LambdaExpression concat)
 => ExpressionFactory.Concat(expr, concat);
Ejemplo n.º 8
0
 public static Expression ConvertReplaceParameters(this LambdaExpression exp, params Expression[] replace)
 => ExpressionFactory.ConvertReplaceParameters(exp, replace);
Ejemplo n.º 9
0
 public ContainsBuilder(ExpressionFactory factory)
 {
     _method  = typeof(NonStrictStringExtensions).GetMethod("Contains");
     _factory = factory;
 }
Ejemplo n.º 10
0
 public BoolHandle(bool value)
 {
     this.expression = ExpressionFactory.BoolInterpretation(value);
 }
Ejemplo n.º 11
0
 public static BoolHandle Implies(BoolHandle left, BoolHandle right)
 {
     return((BoolHandle)ExpressionFactory.Implies(left.Expression, right.Expression));
 }
Ejemplo n.º 12
0
 public static BoolHandle operator !=(BoolHandle left, BoolHandle right)
 {
     return((BoolHandle)ExpressionFactory.Distinct(left.Expression, right.Expression));
 }
Ejemplo n.º 13
0
 private static MemberAssignment BindAssignableExpression(PropertyMap propertyMap, ExpressionResolutionResult result)
 => Expression.Bind(propertyMap.DestinationMember, ExpressionFactory.ToType(result.ResolutionExpression, propertyMap.DestinationType));
Ejemplo n.º 14
0
 public SUBTRACT_Instruction(MonoLangParser.VarContext varContext, MonoLangParser.ExpressionContext[] expressionContext)
 {
     _variable   = VariableFactory.BuildVariable(varContext);
     _expression = ExpressionFactory.BuildExpression(expressionContext[0]);
 }
Ejemplo n.º 15
0
 public abstract Expression Parse(IEnumerable <Token> postFixTokens, ExpressionFactory expressionFactory);
Ejemplo n.º 16
0
 private DialogueExpression Consume_DialogueExpression()
 {
     return(ExpressionFactory.CreateDialogueExpression(Consume_TextMemberExpression(), Consume_DialogueMemberList(), currentToken));
 }
            private static Expression <UntypedMapperFunc> Wrap(MapRequest mapRequest, Delegate typedDelegate)
            {
                var sourceParameter          = Expression.Parameter(typeof(object), "source");
                var destinationParameter     = Expression.Parameter(typeof(object), "destination");
                var contextParameter         = Expression.Parameter(typeof(ResolutionContext), "context");
                var requestedSourceType      = mapRequest.RequestedTypes.SourceType;
                var requestedDestinationType = mapRequest.RequestedTypes.DestinationType;

                var destination = requestedDestinationType.IsValueType() ? Expression.Coalesce(destinationParameter, Expression.New(requestedDestinationType)) : (Expression)destinationParameter;

                // Invoking a delegate here
                return(Expression.Lambda <UntypedMapperFunc>(
                           ExpressionFactory.ToType(
                               Expression.Invoke(Expression.Constant(typedDelegate), ExpressionFactory.ToType(sourceParameter, requestedSourceType), ExpressionFactory.ToType(destination, requestedDestinationType), contextParameter)
                               , typeof(object)),
                           sourceParameter, destinationParameter, contextParameter));
            }
Ejemplo n.º 18
0
 public static BoolHandle operator !(BoolHandle handle)
 {
     return((BoolHandle)ExpressionFactory.Not(handle.Expression));
 }
Ejemplo n.º 19
0
        protected void AppendSelectList(IDictionary <string, object> viewData, object dataItem)
        {
            object selectedValue;

            if (!Data.Any(i => i.Selected))
            {
                selectedValue = ((Expression <Func <TModel, TValue> >)System.Linq.Expressions.Expression.Lambda(typeof(Func <TModel, TValue>), ExpressionFactory.LiftMemberAccessToNull(Expression.Body), Expression.Parameters)).Compile().Invoke((TModel)dataItem);
            }
            else
            {
                selectedValue = Data.SelectedValue;
            }

            viewData.Add(Member + "_Data", new SelectList(Data.Items, Data.DataValueField, Data.DataTextField, selectedValue));
        }
Ejemplo n.º 20
0
 public static BoolHandle operator ^(BoolHandle left, BoolHandle right)
 {
     return((BoolHandle)ExpressionFactory.Xor(left.Expression, right.Expression));
 }
Ejemplo n.º 21
0
 public static Expression Replace(this Expression exp, Expression old, Expression replace)
 => ExpressionFactory.Replace(exp, old, replace);
Ejemplo n.º 22
0
        public IErrorReporter ErrorInvalidDefinitions()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                }.SetMutability(mutability));
                var root_ns = env.Root;

                Extension ext = root_ns.AddNode(Extension.Create());

                // `this` parameter as the second one --> error
                FunctionParameter second_this_param = FunctionParameter.Create("y",
                                                                               NameFactory.ReferenceNameReference(NameFactory.Nat8NameReference()), EntityModifier.This);
                ext.AddBuilder(FunctionBuilder.Create("second_this", NameFactory.Nat8NameReference(), Block.CreateStatement(
                                                          Return.Create(ExpressionFactory.Mul("x", "y"))))
                               .Parameters(FunctionParameter.Create("x", NameFactory.ReferenceNameReference(NameFactory.Nat8NameReference())),
                                           second_this_param));

                // `this` parameter as optional one --> error
                FunctionParameter opt_this_param = FunctionParameter.Create("a",
                                                                            NameFactory.ReferenceNameReference(NameFactory.Nat8NameReference()), Variadic.None,
                                                                            Nat8Literal.Create("0"), false, EntityModifier.This);
                ext.AddBuilder(FunctionBuilder.Create("opt_this", NameFactory.Nat8NameReference(), Block.CreateStatement(
                                                          Return.Create(ExpressionFactory.Mul("a", "a"))))
                               .Parameters(opt_this_param));

                // variadic `this` parameter --> error
                FunctionParameter variadic_this_param = FunctionParameter.Create("b",
                                                                                 NameFactory.ReferenceNameReference(NameFactory.Nat8NameReference()),
                                                                                 Variadic.Create(2, 3), null, false, EntityModifier.This);
                FunctionCall b_count = FunctionCall.Create(NameReference.Create("b", NameFactory.IIterableCount));
                ext.AddBuilder(FunctionBuilder.Create("variadic_this", NameFactory.SizeNameReference(),
                                                      Block.CreateStatement(
                                                          // this is invalid as well, because it would mean we array of references and we try to make
                                                          // a template function (`count`) executed with reference as its template argument
                                                          // return b.count()
                                                          Return.Create(b_count)))
                               .Parameters(variadic_this_param)
                               .Include(NameFactory.LinqExtensionReference()));

                // `this` parameter as value (no reference) --> error
                FunctionParameter value_this_param = FunctionParameter.Create("c", NameFactory.Nat8NameReference(), EntityModifier.This);
                ext.AddBuilder(FunctionBuilder.Create("value_this", NameFactory.Nat8NameReference(), Block.CreateStatement(
                                                          Return.Create(ExpressionFactory.Mul("c", "c"))))
                               .Parameters(value_this_param));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(5, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.NonPrimaryThisParameter, second_this_param));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.OptionalThisParameter, opt_this_param));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.VariadicThisParameter, variadic_this_param));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.NonReferenceThisParameter, value_this_param));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.ReferenceAsTypeArgument, b_count.Name.TemplateArguments.Single()));
            }

            return(resolver);
        }
Ejemplo n.º 23
0
 public static Expression NullCheck(this Expression expression, Type destinationType)
 => ExpressionFactory.NullCheck(expression, destinationType);
Ejemplo n.º 24
0
 public MemberBuilder(ExpressionFactory factory)
 {
     _factory = factory;
 }
Ejemplo n.º 25
0
 public LambdaExpression[] GetUntypedIncludedMembers() =>
 SourceType.IsGenericTypeDefinition ?
 Array.Empty <LambdaExpression>() :
 IncludedMembersNames.Select(name => ExpressionFactory.MemberAccessLambda(SourceType, name)).ToArray();
Ejemplo n.º 26
0
 public static IExpression Parse(ExpressionFactory factory, Parser parser)
 => new IdentifierExpression(parser.CurrentToken());
Ejemplo n.º 27
0
 public void ThrowProtoException(Operand message)
 {
     Throw(ExpressionFactory.New(typeof(ProtoException), message));
 }
Ejemplo n.º 28
0
 public static IExpression Parse(IExpression left, ExpressionFactory factory, Parser parser)
 {
     throw new System.NotImplementedException();
 }
Ejemplo n.º 29
0
 public void ThrowNotSupportedException(Operand message)
 {
     Throw(ExpressionFactory.New(typeof(NotSupportedException), message));
 }
Ejemplo n.º 30
0
 public COMPARE_Instruction(MonoLangParser.ExpressionContext[] context)
 {
     _leftExpression  = ExpressionFactory.BuildExpression(context[0]);
     _rightExpression = ExpressionFactory.BuildExpression(context[1]);
 }
Ejemplo n.º 31
0
        public static void Main(string[] args)
        {
            Console.WriteLine ("Generating random points:");

            List<Problem<Chromosome<int>>> problems = new List<Problem<Chromosome<int>>> ();

            for (int i=0; i<POINT_AMOUNT; i++) {

                int x = rnd.Next (MIN_INT, MAX_INT);

                //
                // TARGET FORMULA
                //

                int y = x % 5;

                Console.WriteLine ("(" + x.ToString () + "," + y.ToString () + ")");

                problems.Add (new PointProblem<Chromosome<int>> (x, y));

            }

            bool useCache = true;
            int generations = 100;
            int populationSize = 1000;
            int selectionSize = 100;
            int mutationSize = 500;

            bool run = true;

            while (run) {

                Console.WriteLine ("Use caching in problem set ( " + useCache + " ) ?");
                string newUseCache = Console.ReadLine ();
                if (newUseCache != "")
                    useCache = readYNstring (newUseCache);

                //  `System.Collections.Generic.List<Genetic.Programming.Arithmetic.PointProblem<Genetic.Programming.Genome.Chromosome<int>>>'
                //  `System.Collections.Generic.List<Genetic.Problem<Genetic.Programming.Genome.Chromosome<int>>>'

                ProblemSet<Chromosome<int>> tester = new ProblemSet<Chromosome<int>> (problems, useCache);

                Console.WriteLine ("Input generations amount ( " + generations + " ):");
                string newGenerations = Console.ReadLine ();
                if (newGenerations != "")
                    generations = Convert.ToInt32 (newGenerations);

                Console.WriteLine ("Input population size ( " + populationSize + " ):");
                string newPopulationSize = Console.ReadLine ();
                if (newPopulationSize != "")
                    populationSize = Convert.ToInt32 (newPopulationSize);

                Console.WriteLine ("Input selection size ( " + selectionSize + " ): ");
                string newSelectionSize = Console.ReadLine ();
                if (newSelectionSize != "")
                    selectionSize = Convert.ToInt32 (newSelectionSize);

                Console.WriteLine ("Input mutation size ( " + mutationSize + " ): ");
                string newMutationSize = Console.ReadLine ();
                if (newMutationSize != "")
                    mutationSize = Convert.ToInt32 (newMutationSize);

                List<Expression<int>> operations = new List<Expression<int>> ();

                operations.Add (new Expression<int> (typeof(Addition)));
                operations.Add (new Expression<int> (typeof(Subtraction)));
                operations.Add (new Expression<int> (typeof(Multiplication)));
                operations.Add (new Expression<int> (typeof(Division)));
                operations.Add (new Expression<int> (typeof(Conditional)));
                operations.Add (new Expression<int> (typeof(Maximum)));
                operations.Add (new Expression<int> (typeof(Minimum)));
                operations.Add (new Expression<int> (typeof(Modulo)));
                operations.Add (new Expression<int> (typeof(Pop<int>)));
                operations.Add (new Expression<int> (typeof(Push<int>)));
                operations.Add (new Expression<int> (typeof(Input<int>)));

                operations.Add (new ConstantExpression<int> (1));
                operations.Add (new ConstantExpression<int> (2));
                operations.Add (new ConstantExpression<int> (0));

                ExpressionFactory<int> factory = new ExpressionFactory<int> (operations);

                Chromosome<int>.factory = factory;

                Evolution<Chromosome<int>> evolution = new Evolution<Chromosome<int>> (generations,
                                                                                        populationSize,
                                                                                        selectionSize,
                                                                                        mutationSize,
                                                                                        tester, false);

                Chromosome<int> winner = evolution.win ();

                Console.WriteLine ("Evolution result: " + winner.ToString ());

                tester.test (winner, true);

                foreach (PointProblem<Chromosome<int>> problem in problems) {

                    int x = problem.task.input;
                    int y = winner.Compute (problem.task);
                    int expectedY = problem.result;

                    Console.WriteLine ((y == expectedY ? "+" : "-") + " f(" + x + ") = " + y + " : " + expectedY);

                }

                if (winner is IMeasurable)
                    Console.WriteLine ("Complexity: " + ((IMeasurable)winner).Complexity ());

                Console.WriteLine ("Fitness: " + tester.test (winner));

                Console.WriteLine ("Do you want to run again (Y/N)?");
                string runAgain = Console.ReadLine ();

                run = readYNstring (runAgain);

            }
        }
Ejemplo n.º 32
0
        void Initialize(Universe universe, string assemblyName, AssemblyBuilderAccess access, CompilerOptions options, ITypeMapper typeMapper = null)
        {
            if (universe == null) throw new ArgumentNullException(nameof(universe));
            if (options == null) throw new ArgumentNullException(nameof(options));
            _compilerOptions = options;
            if (typeMapper == null)
#if FEAT_IKVM
                typeMapper = new TypeMapper(universe);
#else
                typeMapper = new TypeMapper();
#endif
            ExpressionFactory = new ExpressionFactory(typeMapper);
            StaticFactory = new StaticFactory(typeMapper);

#if SILVERLIGHT
            bool save = false;
#else
            bool save = (access & AssemblyBuilderAccess.Save) != 0;
#endif
            string path = options.OutputPath;
            if (path == null && save) throw new ArgumentNullException("options.OutputPath");

            Universe = universe;

            TypeMapper = typeMapper;
            _access = access;

            if (Helpers.IsNullOrEmpty(assemblyName))
            {
                if (save) throw new ArgumentNullException(nameof(assemblyName));
                assemblyName = Guid.NewGuid().ToString();
            }
            
            string moduleName = path == null ? assemblyName : assemblyName + Path.GetExtension(path);

            _fileName = path;

            AssemblyName an = new AssemblyName();
            an.Name = assemblyName;

            AssemblyBuilder =
#if !SILVERLIGHT
                path != null ? Universe.DefineDynamicAssembly(an, access, Path.GetDirectoryName(path)) :
#endif
                    Universe.DefineDynamicAssembly(an, access);
#if FEAT_IKVM
            if (!Helpers.IsNullOrEmpty(options.KeyFile))
            {
               AssemblyBuilder.__SetAssemblyKeyPair(new StrongNameKeyPair(File.OpenRead(options.KeyFile)));
            }
            else if (!Helpers.IsNullOrEmpty(options.KeyContainer))
            {
                AssemblyBuilder.__SetAssemblyKeyPair(new StrongNameKeyPair(options.KeyContainer));
            }
            else if (!Helpers.IsNullOrEmpty(options.PublicKey))
            {
                AssemblyBuilder.__SetAssemblyPublicKey(FromHex(options.PublicKey));
            }
            if (!Helpers.IsNullOrEmpty(options.ImageRuntimeVersion) && options.MetaDataVersion != 0)
            {
                AssemblyBuilder.__SetImageRuntimeVersion(options.ImageRuntimeVersion, options.MetaDataVersion);
            }
            ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName, path, options.SymbolInfo);
#else
            if (save)
            {
#if !SILVERLIGHT
                ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName, Path.GetFileName(path));
#else
                throw new NotSupportedException("Can't save on this platform");
#endif
            }
            else
                ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName);
#endif
        }
Ejemplo n.º 33
0
 public WRITE_Instruction(MonoLangParser.PortContext portContext, MonoLangParser.ExpressionContext[] expressionContext)
 {
     _portName         = portContext.name().NAME().GetText();
     _outputExpression = ExpressionFactory.BuildExpression(expressionContext[0]);
 }
        private static LambdaExpression GenerateTypeMapExpression(MapRequest mapRequest, TypeMap typeMap)
        {
            var mapExpression               = typeMap.MapExpression;
            var typeMapSourceParameter      = mapExpression.Parameters[0];
            var typeMapDestinationParameter = mapExpression.Parameters[1];
            var requestedSourceType         = mapRequest.RequestedTypes.SourceType;
            var requestedDestinationType    = mapRequest.RequestedTypes.DestinationType;

            if (typeMapSourceParameter.Type != requestedSourceType || typeMapDestinationParameter.Type != requestedDestinationType)
            {
                var requestedSourceParameter      = Expression.Parameter(requestedSourceType, "source");
                var requestedDestinationParameter = Expression.Parameter(requestedDestinationType, "typeMapDestination");
                var contextParameter = Expression.Parameter(typeof(ResolutionContext), "context");

                mapExpression = Expression.Lambda(ExpressionFactory.ToType(Expression.Invoke(typeMap.MapExpression,
                                                                                             ExpressionFactory.ToType(requestedSourceParameter, typeMapSourceParameter.Type),
                                                                                             ExpressionFactory.ToType(requestedDestinationParameter, typeMapDestinationParameter.Type),
                                                                                             contextParameter
                                                                                             ), mapRequest.RuntimeTypes.DestinationType),
                                                  requestedSourceParameter, requestedDestinationParameter, contextParameter);
            }

            return(mapExpression);
        }