Пример #1
0
 private static ExpressionCompileResult Compile(ResolveResult rr, ITypeDefinition currentType, IMethod currentMethod, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, bool returnValueIsImportant, Dictionary <IVariable, VariableData> variables, ISet <string> usedVariableNames)
 {
     variables         = variables ?? new Dictionary <IVariable, VariableData>();
     usedVariableNames = usedVariableNames ?? new HashSet <string>();
     return(new ExpressionCompiler(compilation,
                                   metadataImporter,
                                   namer,
                                   runtimeLibrary,
                                   errorReporter,
                                   variables,
                                   new Dictionary <LambdaResolveResult, NestedFunctionData>(),
                                   t => {
         string name = namer.GetVariableName(null, usedVariableNames);
         IVariable variable = new SimpleVariable(t, "temporary", DomRegion.Empty);
         variables[variable] = new VariableData(name, null, false);
         usedVariableNames.Add(name);
         return variable;
     },
                                   _ => { throw new Exception("Cannot compile nested functions here"); },
                                   null,
                                   new NestedFunctionContext(EmptyList <IVariable> .Instance),
                                   null,
                                   currentMethod,
                                   currentType
                                   ).Compile(rr, returnValueIsImportant));
 }
Пример #2
0
    static IEnumerable <bool> personWithSimpleVariable(SimpleVariable Person)
    {
        Person._value = "Chelsea";
        yield return(false);

        Person._value = "Hillary";
        yield return(false);

        Person._value = "Bill";
        yield return(false);
    }
Пример #3
0
            ExpressionType TranslateVariable(SimpleVariable var)
            {
                Entry ent = Env.ValueEnvironment[var.Name] as Entry;

                if (ent is VariableEntry)
                {
                    VariableEntry vent = ent as VariableEntry;
                    return(new ExpressionType(Translate.TranslateSimpleVar(vent.Access, Level), vent.Type));
                }
                else
                {
                    Error.Report(var.Pos, "Undefined variable");
                    return(new ExpressionType(null, Types.Type._unknown));
                }
            }
Пример #4
0
    public override int Eval(Stack st)
    {
        int narg    = GetNarg(st);
        var code_in = GetList(st);

        var fname = GetSymbol(st).Substring(1);
        int nvar  = GetNarg(st);

        var vars = new SimpleVariable[nvar];

        for (int i = 0; i < nvar; i++)
        {
            vars[i] = new SimpleVariable(GetSymbol(st));
        }

        Lambda func = null;
        var    env  = new Environment();
        var    ups  = new Stack();

        object y = null;

        if (nvar == 1)
        {
            int res = UserProgram.process_block(code_in, ups, env, false);

            if (res != Processor.ERROR)
            {
                y = ups.Pop();
            }
        }

        if (y is Algebraic)
        {
            func = new UserFunction(fname, vars, ( Algebraic )y, null, null);
        }
        else
        {
            func = new UserProgram(fname, vars, code_in, null, env, ups);
        }

        pc.env.putValue(fname, func);
        st.Push(fname);

        return(0);
    }
Пример #5
0
        public IVariable GetVariable(string argument)
        {
            string cmd;
            var    locations = IndexerParser.ParseComplexOperation(argument, out cmd);
            var    values    = locations.Select(GetByte);
            var    ret       = new SimpleVariable();

            switch (cmd)
            {
            case "sum":
                ulong sum = 0;
                foreach (var item in values)
                {
                    sum += item;
                }
                ret.Set(sum);
                break;

            case "avg": ret.Set(values.Average(x => x)); break;

            case "min": ret.Set(values.Min()); break;

            case "max": ret.Set(values.Max()); break;

            case "xor":
                byte xor = 0;
                foreach (var item in values)
                {
                    xor ^= item;
                }
                ret.Set(xor);
                break;

            default: break;
            }
            return(ret);
        }
Пример #6
0
        private static JsExpression ConstructConstructorInfo(IMethod constructor, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Func <IType, JsExpression> instantiateType, bool includeDeclaringType)
        {
            var properties = GetCommonMemberInfoProperties(constructor, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType);

            var sem = metadataImporter.GetConstructorSemantics(constructor);

            if (sem.Type == ConstructorScriptSemantics.ImplType.NotUsableFromScript)
            {
                errorReporter.Message(Messages._7200, constructor.FullName);
                return(JsExpression.Null);
            }
            properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Constructor)));
            properties.Add(new JsObjectLiteralProperty("params", JsExpression.ArrayLiteral(constructor.Parameters.Select(p => instantiateType(p.Type)))));
            if (sem.Type == ConstructorScriptSemantics.ImplType.NamedConstructor || sem.Type == ConstructorScriptSemantics.ImplType.StaticMethod)
            {
                properties.Add(new JsObjectLiteralProperty("sname", JsExpression.String(sem.Name)));
            }
            if (sem.Type == ConstructorScriptSemantics.ImplType.StaticMethod)
            {
                properties.Add(new JsObjectLiteralProperty("sm", JsExpression.True));
            }
            if ((sem.Type == ConstructorScriptSemantics.ImplType.UnnamedConstructor || sem.Type == ConstructorScriptSemantics.ImplType.NamedConstructor || sem.Type == ConstructorScriptSemantics.ImplType.StaticMethod) && sem.ExpandParams)
            {
                properties.Add(new JsObjectLiteralProperty("exp", JsExpression.True));
            }
            if (sem.Type == ConstructorScriptSemantics.ImplType.Json || sem.Type == ConstructorScriptSemantics.ImplType.InlineCode)
            {
                var usedNames  = new HashSet <string>();
                var parameters = new List <IVariable>();
                var variables  = new Dictionary <IVariable, VariableData>();
                IList <ResolveResult> constructorParameters = null;
                IList <ResolveResult> initializerStatements = null;
                if (sem.Type == ConstructorScriptSemantics.ImplType.Json && constructor.DeclaringType.Kind == TypeKind.Anonymous)
                {
                    initializerStatements = new List <ResolveResult>();
                    foreach (var p in constructor.DeclaringType.GetProperties())
                    {
                        string paramName = MakeCamelCase(p.Name);
                        string name      = namer.GetVariableName(paramName, usedNames);
                        usedNames.Add(name);
                        var variable = new SimpleVariable(p.ReturnType, paramName, DomRegion.Empty);
                        parameters.Add(variable);
                        variables.Add(variable, new VariableData(name, null, false));
                        initializerStatements.Add(new OperatorResolveResult(p.ReturnType, ExpressionType.Assign, new MemberResolveResult(new InitializedObjectResolveResult(constructor.DeclaringType), p), new LocalResolveResult(variable)));
                    }
                }
                else
                {
                    constructorParameters = new List <ResolveResult>();
                    foreach (var p in constructor.Parameters)
                    {
                        string name = namer.GetVariableName(p.Name, usedNames);
                        usedNames.Add(name);
                        var variable = new SimpleVariable(p.Type, p.Name, DomRegion.Empty);
                        parameters.Add(variable);
                        variables.Add(variable, new VariableData(name, null, false));
                        constructorParameters.Add(new LocalResolveResult(variable));
                    }
                }
                var compileResult = CompileConstructorInvocation(constructor, initializerStatements, constructor.DeclaringTypeDefinition, constructor, constructorParameters, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, variables, usedNames);
                var definition    = JsExpression.FunctionDefinition(parameters.Select(p => variables[p].Name), JsStatement.Block(compileResult.AdditionalStatements.Concat(new[] { JsStatement.Return(compileResult.Expression) })));
                properties.Add(new JsObjectLiteralProperty("def", definition));
            }
            return(JsExpression.ObjectLiteral(properties));
        }
Пример #7
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public Algebraic integrate(Variable var) throws JasymcaException
    public override Algebraic integrate(Variable item)
    {
        Algebraic tmp = Zahl.ZERO;

        for (int i = 1; i < a.Length; i++)
        {
            if (!a[i].depends(item))
            {
                if (item.Equals(this.v))
                {
                    tmp = tmp.add(a[i].mult((new Polynomial(item)).pow_n(i + 1).div(new Unexakt(i + 1))));
                }
                else if (this.v is FunctionVariable && ((FunctionVariable)this.v).arg.depends(item))
                {
                    if (i == 1)
                    {
                        tmp = tmp.add(((FunctionVariable)this.v).integrate(item).mult(a[1]));
                    }
                    else
                    {
                        throw new JasymcaException("Integral not supported.");
                    }
                }
                else
                {
                    tmp = tmp.add(a[i].mult((new Polynomial(item)).mult((new Polynomial(this.v)).pow_n(i))));
                }
            }
            else if (item.Equals(this.v))
            {
                throw new JasymcaException("Integral not supported.");
            }
            else if (this.v is FunctionVariable && ((FunctionVariable)this.v).arg.depends(item))
            {
                if (i == 1 && a[i] is Polynomial && ((Polynomial)a[i]).v.Equals(item))
                {
                    debug("Trying to isolate inner derivative " + this);
                    try
                    {
                        FunctionVariable f = (FunctionVariable)this.v;
                        Algebraic        w = f.arg;
                        Algebraic        q = a[i].div(w.deriv(item));
                        if (q.deriv(item).Equals(Zahl.ZERO))
                        {
                            SimpleVariable v = new SimpleVariable("v");
                            Algebraic      p = FunctionVariable.create(f.fname, new Polynomial(v));
                            Algebraic      r = p.integrate(v).value(v, w).mult(q);
                            tmp = tmp.add(r);
                            continue;
                        }
                    }
                    catch (JasymcaException)
                    {
                    }
                    debug("Failed.");
                    for (int k = 0; k < ((Polynomial)a[i]).a.Length; k++)
                    {
                        if (((Polynomial)a[i]).a[k].depends(item))
                        {
                            throw new JasymcaException("Function not supported by this method");
                        }
                    }
                    if (loopPartial)
                    {
                        loopPartial = false;
                        debug("Partial Integration Loop detected.");
                        throw new JasymcaException("Partial Integration Loop: " + this);
                    }
                    debug("Trying partial integration: x^n*f(x) , n-times diff " + this);
                    try
                    {
                        loopPartial = true;
                        Algebraic _p = a[i];
                        Algebraic f  = ((FunctionVariable)this.v).integrate(item);
                        Algebraic r  = f.mult(_p);
                        while (!(_p = _p.deriv(item)).Equals(Zahl.ZERO))
                        {
                            f = f.integrate(item).mult(Zahl.MINUS);
                            r = r.add(f.mult(_p));
                        }
                        loopPartial = false;
                        tmp         = tmp.add(r);
                        continue;
                    }
                    catch (JasymcaException)
                    {
                        loopPartial = false;
                    }
                    debug("Failed.");
                    debug("Trying partial integration: x^n*f(x) , 1-times int " + this);
                    try
                    {
                        loopPartial = true;
                        Algebraic p1 = a[i].integrate(item);
                        Algebraic f  = new Polynomial((FunctionVariable)this.v);
                        Algebraic r  = p1.mult(f).sub(p1.mult(f.deriv(item)).integrate(item));
                        loopPartial = false;
                        tmp         = tmp.add(r);
                        continue;
                    }
                    catch (JasymcaException)
                    {
                        loopPartial = false;
                    }
                    debug("Failed");
                    throw new JasymcaException("Function not supported by this method");
                }
                else
                {
                    throw new JasymcaException("Integral not supported.");
                }
            }
            else
            {
                tmp = tmp.add(a[i].integrate(item).mult((new Polynomial(this.v)).pow_n(i)));
            }
        }
        if (a.Length > 0)
        {
            tmp = tmp.add(a[0].integrate(item));
        }
        return(tmp);
    }
Пример #8
0
        public object ObjRef()
        {
            var tag = (SerializationCode)Byte();

            if (Config.SerTrace)
            {
                Console.WriteLine("Reading {0} from {1}...", tag, rpointer - 1);
            }
            int i, j;

            switch (tag)
            {
            case SerializationCode.Null:
                return(null);

            case SerializationCode.ForeignRef:
                i = Int();
                j = Int();
                return(unit_map[i].bynum[j]);

            case SerializationCode.SelfRef:
                i = Int();
                return(unit.bynum[i]);

            case SerializationCode.NewUnitRef:
                return(LoadNewUnit());

            case SerializationCode.RuntimeUnit:
                return(RuntimeUnit.Thaw(this));

            case SerializationCode.SubInfo:
                return(SubInfo.Thaw(this));

            case SerializationCode.STable:
                return(STable.Thaw(this));

            case SerializationCode.StashEnt:
                return(StashEnt.Thaw(this));

            case SerializationCode.Rat:
                return(Rat.Thaw(this));

            case SerializationCode.FatRat:
                return(FatRat.Thaw(this));

            case SerializationCode.Complex:
                return(Complex.Thaw(this));

            case SerializationCode.BigInteger:
                return(BigInteger.Thaw(this));

            case SerializationCode.VarDeque:
                return(VarDeque.Thaw(this));

            case SerializationCode.VarHash:
                return(VarHash.Thaw(this));

            case SerializationCode.DispatchEnt:
                return(DispatchEnt.Thaw(this));

            //case SerializationCode.RxFrame:
            //    return RxFrame.Thaw(this);
            case SerializationCode.P6how:
                return(P6how.Thaw(this));

            case SerializationCode.CC:
                return(CC.Thaw(this));

            case SerializationCode.AltInfo:
                return(AltInfo.Thaw(this));

            case SerializationCode.Signature:
                return(Signature.Thaw(this));

            case SerializationCode.Parameter:
                return(Parameter.Thaw(this));

            case SerializationCode.ReflectObj:
                return(ReflectObj.Thaw(this));

            case SerializationCode.P6opaque:
                return(P6opaque.Thaw(this));

            case SerializationCode.Frame:
                return(Frame.Thaw(this));

            //Cursor,

            case SerializationCode.String:
                return(Register(String()));

            case SerializationCode.ArrP6any:
                return(RefsARegister <P6any>());

            case SerializationCode.ArrVariable:
                return(RefsARegister <Variable>());

            case SerializationCode.ArrString:
                return(RefsARegister <string>());

            case SerializationCode.ArrCC:
                return(RefsARegister <CC>());

            case SerializationCode.Boolean:
                return(Register(Byte() != 0));

            case SerializationCode.Int:
                return(Register(Int()));

            case SerializationCode.Double:
                return(Register(Double()));

            case SerializationCode.Type:
                return(Register(Type.GetType(String(), true)));

            case SerializationCode.SimpleVariable:
            case SerializationCode.SimpleVariable_1:
            case SerializationCode.SimpleVariable_2:
            case SerializationCode.SimpleVariable_3:
                return(SimpleVariable.Thaw(this,
                                           (int)tag - (int)SerializationCode.SimpleVariable));

            case SerializationCode.SubstrLValue:
                return(SubstrLValue.Thaw(this));

            case SerializationCode.TiedVariable:
                return(TiedVariable.Thaw(this));

            case SerializationCode.SubViviHook:
                return(SubViviHook.Thaw(this));

            case SerializationCode.ArrayViviHook:
                return(ArrayViviHook.Thaw(this));

            case SerializationCode.NewArrayViviHook:
                return(NewArrayViviHook.Thaw(this));

            case SerializationCode.HashViviHook:
                return(HashViviHook.Thaw(this));

            case SerializationCode.NewHashViviHook:
                return(NewHashViviHook.Thaw(this));

            case SerializationCode.LADNone:
                return(Register(new LADNone()));

            case SerializationCode.LADNull:
                return(Register(new LADNull()));

            case SerializationCode.LADDot:
                return(Register(new LADDot()));

            case SerializationCode.LADDispatcher:
                return(Register(new LADDispatcher()));

            case SerializationCode.LADImp:
                return(Register(new LADImp()));

            case SerializationCode.LADStr:
                return(LADStr.Thaw(this));

            case SerializationCode.LADStrNoCase:
                return(LADStrNoCase.Thaw(this));

            case SerializationCode.LADMethod:
                return(LADMethod.Thaw(this));

            case SerializationCode.LADParam:
                return(LADParam.Thaw(this));

            case SerializationCode.LADQuant:
                return(LADQuant.Thaw(this));

            case SerializationCode.LADSequence:
                return(LADSequence.Thaw(this));

            case SerializationCode.LADAny:
                return(LADAny.Thaw(this));

            case SerializationCode.LADCC:
                return(LADCC.Thaw(this));

            default:
                throw new ThawException("unexpected object tag " + tag);
            }
        }
Пример #9
0
        public static Vector Horowitz(Algebraic p, Polynomial q, Variable x)
        {
            if (Poly.Degree(p, x) >= Poly.Degree(q, x))
            {
                throw new SymbolicException("Degree of p must be smaller than degree of q");
            }

            p = p.Rat();

            q = ( Polynomial )q.Rat();

            var d = Poly.poly_gcd(q, q.Derive(x));
            var b = Poly.polydiv(q, d);

            var m = b is Polynomial ? (( Polynomial )b).Degree() : 0;
            var n = d is Polynomial ? (( Polynomial )d).Degree() : 0;

            var a = new SimpleVariable[m];
            var X = new Polynomial(x);

            Algebraic A = Symbol.ZERO;

            for (var i = a.Length - 1; i >= 0; i--)
            {
                a[i] = new SimpleVariable("a" + i);

                A = A + new Polynomial(a[i]);

                if (i > 0)
                {
                    A = A * X;
                }
            }

            var c = new SimpleVariable[n];

            Algebraic C = Symbol.ZERO;

            for (var i = c.Length - 1; i >= 0; i--)
            {
                c[i] = new SimpleVariable("c" + i);

                C = C + new Polynomial(c[i]);

                if (i > 0)
                {
                    C = C * X;
                }
            }

            var r = Poly.polydiv(C * b * d.Derive(x), d);

            r = b * C.Derive(x) - r + d * A;

            var aik = Matrix.CreateRectangularArray <Algebraic>(m + n, m + n);

            Algebraic cf;

            var co = new Algebraic[m + n];

            for (var i = 0; i < m + n; i++)
            {
                co[i] = Poly.Coefficient(p, x, i);

                cf = Poly.Coefficient(r, x, i);

                for (var k = 0; k < m; k++)
                {
                    aik[i][k] = cf.Derive(a[k]);
                }

                for (var k = 0; k < n; k++)
                {
                    aik[i][k + m] = cf.Derive(c[k]);
                }
            }

            var s = LambdaLINSOLVE.Gauss(new Matrix(aik), new Vector(co));

            A = Symbol.ZERO;

            for (var i = m - 1; i >= 0; i--)
            {
                A = A + s[i];

                if (i > 0)
                {
                    A = A * X;
                }
            }

            C = Symbol.ZERO;

            for (var i = n - 1; i >= 0; i--)
            {
                C = C + s[i + m];

                if (i > 0)
                {
                    C = C * X;
                }
            }

            return(new Vector(new[] { C / d, A / b }));
        }
Пример #10
0
    public override Algebraic Integrate(Variable v)
    {
        Algebraic tmp = Symbolic.ZERO;

        for (int i = 1; i < Coeffs.Length; i++)
        {
            if (!Coeffs[i].Depends(v))
            {
                if (v.Equals(_v))
                {
                    tmp = tmp + Coeffs[i] * (new Polynomial(v) ^ (i + 1)) / new Complex(i + 1);
                }
                else if (_v is FunctionVariable && (( FunctionVariable )_v).Var.Depends(v))
                {
                    if (i == 1)
                    {
                        tmp = tmp + (( FunctionVariable )_v).Integrate(v) * Coeffs[1];
                    }
                    else
                    {
                        throw new JasymcaException("Integral not supported.");
                    }
                }
                else
                {
                    tmp = tmp + Coeffs[i] * (new Polynomial(v) * new Polynomial(_v) ^ i);
                }
            }
            else if (v.Equals(this._v))
            {
                throw new JasymcaException("Integral not supported.");
            }
            else if (this._v is FunctionVariable && ((FunctionVariable)this._v).Var.Depends(v))
            {
                if (i == 1 && Coeffs[i] is Polynomial && ((Polynomial)Coeffs[i])._v.Equals(v))
                {
                    Debug("Trying to isolate inner derivative " + this);

                    try
                    {
                        var f = ( FunctionVariable )_v;

                        var w = f.Var;

                        var q = Coeffs[i] / w.Derive(v);

                        if (Equals(q.Derive(v), Symbolic.ZERO))
                        {
                            var sv = new SimpleVariable("v");

                            var p = FunctionVariable.Create(f.Name, new Polynomial(sv));

                            var r = p.Integrate(sv).Value(sv, w) * q;

                            tmp = tmp + r;

                            continue;
                        }
                    }
                    catch (JasymcaException)
                    {
                    }

                    Debug("Failed.");

                    if ((( Polynomial )Coeffs[i]).Coeffs.Any(t => t.Depends(v)))
                    {
                        throw new JasymcaException("Function not supported by this method");
                    }

                    if (loopPartial)
                    {
                        loopPartial = false;

                        Debug("Partial Integration Loop detected.");

                        throw new JasymcaException("Partial Integration Loop: " + this);
                    }

                    Debug("Trying partial integration: x^n*f(x) , n-times diff " + this);

                    try
                    {
                        loopPartial = true;

                        var c = Coeffs[i];

                        var fv = (( FunctionVariable )_v).Integrate(v);

                        var r = fv * c;

                        while ((c = c.Derive(v)) != Symbolic.ZERO)
                        {
                            r = r - fv.Integrate(v) * c;
                        }

                        loopPartial = false;
                        tmp         = tmp + r;

                        continue;
                    }
                    catch (JasymcaException)
                    {
                        loopPartial = false;
                    }

                    Debug("Failed.");
                    Debug("Trying partial integration: x^n*f(x) , 1-times int " + this);

                    try
                    {
                        loopPartial = true;

                        var p1 = Coeffs[i].Integrate(v);

                        Algebraic f = new Polynomial(( FunctionVariable )_v);

                        var r = p1 * f - (p1 * f.Derive(v)).Integrate(v);

                        loopPartial = false;

                        tmp = tmp + r;

                        continue;
                    }
                    catch (JasymcaException)
                    {
                        loopPartial = false;
                    }

                    Debug("Failed");

                    throw new JasymcaException("Function not supported by this method");
                }
                else
                {
                    throw new JasymcaException("Integral not supported.");
                }
            }
            else
            {
                tmp = tmp + Coeffs[i].Integrate(v) * new Polynomial(_v) ^ i;
            }
        }

        if (Coeffs.Length > 0)
        {
            tmp = tmp + Coeffs[0].Integrate(v);
        }

        return(tmp);
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="SimpleConstructor"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="prefix">The prefix.</param>
 /// <param name="postfix">The postfix.</param>
 public SimpleConstructor(string name, string prefix, string postfix)
 {
     this.prefix = prefix;
     this.postfix = postfix;
     nameAndReturn = new SimpleVariable(name, null, null);
 }
Пример #12
0
 void PrintVariable(SimpleVariable v, int d)
 {
     Say("SimpleVariable(");
     Say(v.Name.ToString());
     Say(")");
 }
Пример #13
0
    static void Main(string[] args)
    {
        Console.WriteLine("Names using a return value:");
        foreach (string p in personWithReturnValue())
        {
            Console.WriteLine(p);
        }

        Console.WriteLine("Names using SimpleVariable:");
        SimpleVariable P = new SimpleVariable();

        foreach (bool l1 in personWithSimpleVariable(P))
        {
            Console.WriteLine(P._value);
        }

        Console.WriteLine("Names using UnifyingVariable:");
        UnifyingVariable Person = new UnifyingVariable();

        foreach (bool l1 in personWithUnify(Person))
        {
            Console.WriteLine(Person._value);
        }

        Console.WriteLine("Use unify to check a person:");
        foreach (bool l1 in Person.unify("Hillary"))
        {
            foreach (bool l2 in personWithUnify(Person))
            {
                Console.WriteLine("Hillary is a person.");
            }
        }
        foreach (bool l1 in Person.unify("Buddy"))
        {
            foreach (bool l2 in personWithUnify(Person))
            {
                // This won't print.
                Console.WriteLine("Buddy is a person.");
            }
        }

        Console.WriteLine("Use generalUnify to check a person:");
        foreach (bool l1 in person("Hillary"))
        {
            Console.WriteLine("Hillary is a person.");
        }
        foreach (bool l1 in person("Buddy"))
        {
            // This won't print.
            Console.WriteLine("Buddy is a person.");
        }

        Console.WriteLine("Find relations:");
        UnifyingVariable Brother = new UnifyingVariable();

        foreach (bool l1 in brother("Hillary", Brother))
        {
            Console.WriteLine("Hillary has brother " +
                              Brother._value + ".");
        }

        Console.WriteLine("Joining functions:");
        UnifyingVariable Uncle = new UnifyingVariable();

        foreach (bool l1 in uncle(Person, Uncle))
        {
            Console.WriteLine(Person._value +
                              " has uncle " + Uncle._value + ".");
        }

        Console.WriteLine("\nPress Enter to finish.");
        Console.ReadLine();
    }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SimpleMethod"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="prefix">The prefix.</param>
 /// <param name="type">The type.</param>
 public SimpleMethod(string name, string prefix, Type type)
 {
     this.prefix = prefix;
     nameAndReturn = new SimpleVariable(name, type, null);
 }
Пример #15
0
        private static JsExpression ConstructMemberInfo(IMember m, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Func <IType, JsExpression> instantiateType, bool includeDeclaringType, MethodScriptSemantics semanticsIfAccessor)
        {
            if (m is IMethod && ((IMethod)m).IsConstructor)
            {
                return(ConstructConstructorInfo((IMethod)m, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType));
            }

            var properties = GetCommonMemberInfoProperties(m, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType);

            if (m.IsStatic)
            {
                properties.Add(new JsObjectLiteralProperty("isStatic", JsExpression.True));
            }

            if (m is IMethod)
            {
                var method = (IMethod)m;
                var sem    = semanticsIfAccessor ?? metadataImporter.GetMethodSemantics(method);
                if (sem.Type != MethodScriptSemantics.ImplType.NormalMethod && sem.Type != MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument && sem.Type != MethodScriptSemantics.ImplType.InlineCode)
                {
                    errorReporter.Message(Messages._7201, m.FullName, "method");
                    return(JsExpression.Null);
                }
                if ((sem.Type == MethodScriptSemantics.ImplType.NormalMethod || sem.Type == MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument) && sem.ExpandParams)
                {
                    properties.Add(new JsObjectLiteralProperty("exp", JsExpression.True));
                }

                properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Method)));
                if (sem.Type == MethodScriptSemantics.ImplType.InlineCode)
                {
                    var usedNames  = new HashSet <string>();
                    var parameters = new List <IVariable>();
                    var variables  = new Dictionary <IVariable, VariableData>();
                    var arguments  = new List <ResolveResult>();
                    foreach (var p in method.Parameters)
                    {
                        string name = namer.GetVariableName(p.Name, usedNames);
                        usedNames.Add(name);
                        var variable = new SimpleVariable(p.Type, p.Name, DomRegion.Empty);
                        parameters.Add(variable);
                        variables.Add(variable, new VariableData(name, null, false));
                        arguments.Add(new LocalResolveResult(variable));
                    }
                    var tokens = InlineCodeMethodCompiler.Tokenize(method, sem.LiteralCode, _ => {});

                    var compileResult = Compile(CreateMethodInvocationResolveResult(method, method.IsStatic ? (ResolveResult) new TypeResolveResult(method.DeclaringType) : new ThisResolveResult(method.DeclaringType), arguments), method.DeclaringTypeDefinition, method, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, true, variables, usedNames);
                    var definition    = JsExpression.FunctionDefinition(parameters.Select(p => variables[p].Name), JsStatement.Block(compileResult.AdditionalStatements.Concat(new[] { JsStatement.Return(compileResult.Expression) })));

                    if (tokens.Any(t => t.Type == InlineCodeToken.TokenType.TypeParameter && t.OwnerType == SymbolKind.Method))
                    {
                        definition = JsExpression.FunctionDefinition(method.TypeParameters.Select(namer.GetTypeParameterName), JsStatement.Return(definition));
                        properties.Add(new JsObjectLiteralProperty("tpcount", JsExpression.Number(method.TypeParameters.Count)));
                    }
                    properties.Add(new JsObjectLiteralProperty("def", definition));
                }
                else
                {
                    if (IsJsGeneric(method, metadataImporter))
                    {
                        properties.Add(new JsObjectLiteralProperty("tpcount", JsExpression.Number(method.TypeParameters.Count)));
                    }
                    if (sem.Type == MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument)
                    {
                        properties.Add(new JsObjectLiteralProperty("sm", JsExpression.True));
                    }
                    properties.Add(new JsObjectLiteralProperty("sname", JsExpression.String(sem.Name)));
                }
                properties.Add(new JsObjectLiteralProperty("returnType", instantiateType(method.ReturnType)));
                properties.Add(new JsObjectLiteralProperty("params", JsExpression.ArrayLiteral(method.Parameters.Select(p => instantiateType(p.Type)))));
            }
            else if (m is IField)
            {
                var field = (IField)m;
                var sem   = metadataImporter.GetFieldSemantics(field);
                if (sem.Type != FieldScriptSemantics.ImplType.Field)
                {
                    errorReporter.Message(Messages._7201, m.FullName, "field");
                    return(JsExpression.Null);
                }
                properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Field)));
                properties.Add(new JsObjectLiteralProperty("returnType", instantiateType(field.ReturnType)));
                properties.Add(new JsObjectLiteralProperty("sname", JsExpression.String(sem.Name)));
            }
            else if (m is IProperty)
            {
                var prop = (IProperty)m;
                var sem  = metadataImporter.GetPropertySemantics(prop);
                properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Property)));
                properties.Add(new JsObjectLiteralProperty("returnType", instantiateType(prop.ReturnType)));
                if (prop.Parameters.Count > 0)
                {
                    properties.Add(new JsObjectLiteralProperty("params", JsExpression.ArrayLiteral(prop.Parameters.Select(p => instantiateType(p.Type)))));
                }

                switch (sem.Type)
                {
                case PropertyScriptSemantics.ImplType.GetAndSetMethods:
                    if (sem.GetMethod != null && sem.GetMethod.Type != MethodScriptSemantics.ImplType.NormalMethod && sem.GetMethod.Type != MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument && sem.GetMethod.Type != MethodScriptSemantics.ImplType.InlineCode)
                    {
                        errorReporter.Message(Messages._7202, m.FullName, "property", "getter");
                        return(JsExpression.Null);
                    }
                    if (sem.SetMethod != null && sem.SetMethod.Type != MethodScriptSemantics.ImplType.NormalMethod && sem.SetMethod.Type != MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument && sem.SetMethod.Type != MethodScriptSemantics.ImplType.InlineCode)
                    {
                        errorReporter.Message(Messages._7202, m.FullName, "property", "setter");
                        return(JsExpression.Null);
                    }
                    if (sem.GetMethod != null)
                    {
                        properties.Add(new JsObjectLiteralProperty("getter", ConstructMemberInfo(prop.Getter, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType, sem.GetMethod)));
                    }
                    if (sem.SetMethod != null)
                    {
                        properties.Add(new JsObjectLiteralProperty("setter", ConstructMemberInfo(prop.Setter, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType, sem.SetMethod)));
                    }
                    break;

                case PropertyScriptSemantics.ImplType.Field:
                    if (prop.CanGet)
                    {
                        properties.Add(new JsObjectLiteralProperty("getter", ConstructFieldPropertyAccessor(prop.Getter, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, sem.FieldName, instantiateType, isGetter: true, includeDeclaringType: includeDeclaringType)));
                    }
                    if (prop.CanSet)
                    {
                        properties.Add(new JsObjectLiteralProperty("setter", ConstructFieldPropertyAccessor(prop.Setter, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, sem.FieldName, instantiateType, isGetter: false, includeDeclaringType: includeDeclaringType)));
                    }
                    properties.Add(new JsObjectLiteralProperty("fname", JsExpression.String(sem.FieldName)));
                    break;

                default:
                    errorReporter.Message(Messages._7201, m.FullName, "property");
                    return(JsExpression.Null);
                }
            }
            else if (m is IEvent)
            {
                var evt = (IEvent)m;
                var sem = metadataImporter.GetEventSemantics(evt);
                if (sem.Type != EventScriptSemantics.ImplType.AddAndRemoveMethods)
                {
                    errorReporter.Message(Messages._7201, m.FullName, "event");
                    return(JsExpression.Null);
                }
                if (sem.AddMethod.Type != MethodScriptSemantics.ImplType.NormalMethod && sem.AddMethod.Type != MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument && sem.AddMethod.Type != MethodScriptSemantics.ImplType.InlineCode)
                {
                    errorReporter.Message(Messages._7202, m.FullName, "event", "add accessor");
                    return(JsExpression.Null);
                }
                if (sem.RemoveMethod.Type != MethodScriptSemantics.ImplType.NormalMethod && sem.RemoveMethod.Type != MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument && sem.RemoveMethod.Type != MethodScriptSemantics.ImplType.InlineCode)
                {
                    errorReporter.Message(Messages._7202, m.FullName, "event", "remove accessor");
                    return(JsExpression.Null);
                }

                properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Event)));
                properties.Add(new JsObjectLiteralProperty("adder", ConstructMemberInfo(evt.AddAccessor, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType, sem.AddMethod)));
                properties.Add(new JsObjectLiteralProperty("remover", ConstructMemberInfo(evt.RemoveAccessor, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType, sem.RemoveMethod)));
            }
            else
            {
                throw new ArgumentException("Invalid member " + m);
            }

            return(JsExpression.ObjectLiteral(properties));
        }
Пример #16
0
 void PrintVariable(SimpleVariable v, int d)
 {
     Say("SimpleVariable(");
     Say(v.Name.ToString());
     Say(")");
 }
Пример #17
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static Vektor horowitz(Algebraic p, Polynomial q, Variable x) throws JasymcaException
    public static Vektor horowitz(Algebraic p, Polynomial q, Variable x)
    {
        if (Poly.degree(p, x) >= Poly.degree(q, x))
        {
            throw new JasymcaException("Degree of p must be smaller than degree of q");
        }
        p = p.rat();
        q = (Polynomial)q.rat();
        Algebraic d = Poly.poly_gcd(q, q.deriv(x));
        Algebraic b = Poly.polydiv(q, d);
        int       m = b is Polynomial? ((Polynomial)b).degree():0;
        int       n = d is Polynomial? ((Polynomial)d).degree():0;

        SimpleVariable[] a = new SimpleVariable[m];
        Polynomial       X = new Polynomial(x);
        Algebraic        A = Zahl.ZERO;

        for (int i = a.Length - 1; i >= 0; i--)
        {
            a[i] = new SimpleVariable("a" + i);
            A    = A.add(new Polynomial(a[i]));
            if (i > 0)
            {
                A = A.mult(X);
            }
        }
        SimpleVariable[] c = new SimpleVariable[n];
        Algebraic        C = Zahl.ZERO;

        for (int i = c.Length - 1; i >= 0; i--)
        {
            c[i] = new SimpleVariable("c" + i);
            C    = C.add(new Polynomial(c[i]));
            if (i > 0)
            {
                C = C.mult(X);
            }
        }
        Algebraic r = Poly.polydiv(C.mult(b).mult(d.deriv(x)), d);

        r = b.mult(C.deriv(x)).sub(r).add(d.mult(A));
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: Algebraic[][] aik = new Algebraic[m+n][m+n];
        Algebraic[][] aik = RectangularArrays.ReturnRectangularAlgebraicArray(m + n, m + n);
        Algebraic     cf; Algebraic[] co = new Algebraic[m + n];

        for (int i = 0; i < m + n; i++)
        {
            co[i] = Poly.coefficient(p, x, i);
            cf    = Poly.coefficient(r, x, i);
            for (int k = 0; k < m; k++)
            {
                aik[i][k] = cf.deriv(a[k]);
            }
            for (int k = 0; k < n; k++)
            {
                aik[i][k + m] = cf.deriv(c[k]);
            }
        }
        Vektor s = LambdaLINSOLVE.Gauss(new Matrix(aik), new Vektor(co));

        A = Zahl.ZERO;
        for (int i = m - 1; i >= 0; i--)
        {
            A = A.add(s.get(i));
            if (i > 0)
            {
                A = A.mult(X);
            }
        }
        C = Zahl.ZERO;
        for (int i = n - 1; i >= 0; i--)
        {
            C = C.add(s.get(i + m));
            if (i > 0)
            {
                C = C.mult(X);
            }
        }
        co    = new Algebraic[2];
        co[0] = C.div(d);
        co[1] = A.div(b);
        return(new Vektor(co));
    }