public FunctionDecl(object f, XmlQualifiedName identity, FunctionParameter[] parameters) { this.f = f; this.identity = identity; this.parameters = parameters; }
public Function(string returnType, string name, FunctionParameter[] parameters, string body) { ReturnType = returnType; Parameters = parameters; Name = name; Body = body; }
private static bool IsDecimal(FunctionParameter param) { PrimitiveType primitive = param.TypeUsage.EdmType as PrimitiveType; if (primitive == null) { return(false); } return(primitive.ClrEquivalentType == typeof(decimal)); }
private static IList <FunctionParameter> GetModelParametersForModelDefinedFunction( this DbModel model, MethodInfo methodInfo) { ParameterInfo[] parameters = methodInfo.GetParameters().ToArray(); return(parameters .Select((parameterInfo) => FunctionParameter.Create( parameterInfo.GetCustomAttribute <ParameterAttribute>()?.Name ?? parameterInfo.Name, model.GetModelStructualType(parameterInfo.ParameterType, methodInfo), ParameterMode.In)) .ToArray()); }
public override void VisitFunctionParameter(FunctionParameter node, CloningAstVisitorContext context) { context.Result = new FunctionParameter() { IsConst = node.IsConst, ParameterQualifier = node.ParameterQualifier, TypeSpecifier = this.CloneNode(node.TypeSpecifier, context), ArraySpecifier = this.CloneNode(node.ArraySpecifier, context), Name = this.CloneNode(node.Name, context) }; }
public virtual void VisitFunctionParameter(FunctionParameter par) { if (par.ParameterType != null) { VisitTypeReference(par.ParameterType); } if (par.DefaultValue != null) { VisitRaw(par.DefaultValue); } }
private FunctionParameter CreateReturnParameter(MethodInfo method, DbModel model) { Type parameterType = method.ReturnType; string parameterName = "return"; PrimitiveType primitiveType = PrimitiveType.GetEdmPrimitiveTypes().FirstOrDefault(t => t.ClrEquivalentType == parameterType); EdmType edmType = model.ProviderManifest.GetStoreType(TypeUsage.CreateDefaultTypeUsage(primitiveType)).EdmType; ParameterMode parameterMode = ParameterMode.ReturnValue; FunctionParameter functionParameter = FunctionParameter.Create(parameterName, edmType, parameterMode); return(functionParameter); }
public FunctionFrame(FunctionFrame original) { Start = original.Start; Returns = original.Returns; Parameters = new List <FunctionParameter> (); foreach (FunctionParameter ofp in original.Parameters) { FunctionParameter copyfp = new FunctionParameter(ofp); Parameters.Add(copyfp); } }
public Label(FunctionParameter func, object objeto, Rectangle rec, IntPtr font, Aligment aligment) { functionParameter = func; this.objeto = objeto; this.rectangle = rec; base.zOrder = 0; this.textData = ""; base.textFont = font; this.aligment = aligment; this.pos.X = rec.X; this.pos.Y = rec.Y; }
public IInterpreter MinLimitVariadicFunctionWithSpread() { var interpreter = new Interpreter.Interpreter(); foreach (var mutability in Options.AllMutabilityModes) { var env = Language.Environment.Create(new Options() { AllowInvalidMainResult = true, DebugThrowOnError = true }.SetMutability(mutability)); var root_ns = env.Root; root_ns.AddBuilder(FunctionBuilder.Create( "sum", ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(new IExpression[] { // let i0 = n.at(0) VariableDeclaration.CreateStatement("i0", null, FunctionCall.Create(NameReference.Create("n", NameFactory.PropertyIndexerName), FunctionArgument.Create(NatLiteral.Create("0")))), // let i1 = n.at(1) VariableDeclaration.CreateStatement("i1", null, FunctionCall.Create(NameReference.Create("n", NameFactory.PropertyIndexerName), FunctionArgument.Create(NatLiteral.Create("1")))), // return i0+i1 Return.Create(ExpressionFactory.Add("i0", "i1")) })) .Parameters(FunctionParameter.Create("n", NameFactory.Int64NameReference(), Variadic.Create(2), null, isNameRequired: false))); var main_func = root_ns.AddBuilder(FunctionBuilder.Create( "main", ExpressionReadMode.OptionalUse, NameFactory.Int64NameReference(), Block.CreateStatement(new IExpression[] { VariableDeclaration.CreateStatement("x", null, ExpressionFactory.HeapConstructor(NameFactory.ChunkNameReference(NameFactory.Int64NameReference()), FunctionArgument.Create(NatLiteral.Create("2"))), env.Options.ReassignableModifier()), Assignment.CreateStatement(FunctionCall.Indexer(NameReference.Create("x"), FunctionArgument.Create(NatLiteral.Create("0"))), Int64Literal.Create("-6")), Assignment.CreateStatement(FunctionCall.Indexer(NameReference.Create("x"), FunctionArgument.Create(NatLiteral.Create("1"))), Int64Literal.Create("8")), Return.Create(FunctionCall.Create(NameReference.Create("sum"), FunctionArgument.Create(Spread.Create(NameReference.Create("x"))))) }))); ExecValue result = interpreter.TestRun(env); Assert.AreEqual(2L, result.RetValue.PlainValue); } return(interpreter); }
private void CreateFunctionParameterFromFunction(object sender, EventArgs args) { FunctionExecution func = (FunctionExecution)tvwCondition.SelectedNode; pol.ApplyBaseReadWrite parentApply = func.ApplyBaseDefinition; pol.FunctionElementReadWrite function = new pol.FunctionElementReadWrite("urn:new_function_param", XacmlVersion.Version11); FunctionParameter node = new FunctionParameter(function); func.Nodes.Add(node); parentApply.Arguments.Add(function); }
private FunctionParameter ConvertToTaupoFunctionParameter(IEdmOperationParameter edmOperationParameter) { var taupoFunctionParameter = new FunctionParameter() { Name = edmOperationParameter.Name, DataType = this.ConvertToTaupoDataType(edmOperationParameter.Type), Mode = FunctionParameterMode.In }; this.ConvertAnnotationsIntoTaupo(edmOperationParameter, taupoFunctionParameter); return(taupoFunctionParameter); }
private void LoadTestFlowConfig(XmlNode xnScequencer) { dgvTestFlow.Rows.Clear(); cParamsByID.Clear(); oListTestFlow = new List <TestFlow>(); XmlNode xnTestFlow = xnScequencer.SelectSingleNode("testflowconfig"); foreach (XmlNode xn in xnTestFlow.ChildNodes) { TestFlow testFlow = new TestFlow(); testFlow.ID = Convert.ToInt32(xn.SelectSingleNode("id").InnerText); cParamsByID.Add(testFlow.ID, new List <FunctionParameter>()); testFlow.TestNumber = Convert.ToInt32(xn.SelectSingleNode("testnumber").InnerText); testFlow.TestName = xn.SelectSingleNode("testname").InnerText; testFlow.TestFunction = xn.SelectSingleNode("testfunction").InnerText; testFlow.UpperLimit = Convert.ToDouble(xn.SelectSingleNode("upperlimit").InnerText); testFlow.LowerLimit = Convert.ToDouble(xn.SelectSingleNode("lowerlimit").InnerText); testFlow.Unit = xn.SelectSingleNode("unit").InnerText; testFlow.SoftBin = Convert.ToInt32(xn.SelectSingleNode("softbin").InnerText); testFlow.HardBin = Convert.ToInt32(xn.SelectSingleNode("hardbin").InnerText); testFlow.Action = xn.SelectSingleNode("action").InnerText; XmlNode xnTestFunctionParameters = xn.SelectSingleNode("testfunctionparameters"); foreach (XmlNode x in xnTestFunctionParameters) { FunctionParameter fp = new FunctionParameter(); fp.ParameterName = x.SelectSingleNode("parametername").InnerText; fp.ParameterType = x.SelectSingleNode("parametertype").InnerText; fp.ParameterValue = x.SelectSingleNode("parametervalue").InnerText; testFlow.TestFunctionParameters.Add(fp); cParamsByID[testFlow.ID].Add(fp); } oListTestFlow.Add(testFlow); int index = dgvTestFlow.Rows.Add(); dgvTestFlow.Rows[index].Cells["ID"].Value = testFlow.ID; dgvTestFlow.Rows[index].Cells["TestNumber"].Value = testFlow.TestNumber; dgvTestFlow.Rows[index].Cells["TestName"].Value = testFlow.TestName; dgvTestFlow.Rows[index].Cells["TestFunction"].Value = testFlow.TestFunction; dgvTestFlow.Rows[index].Cells["UpperLimit"].Value = testFlow.UpperLimit; dgvTestFlow.Rows[index].Cells["LowerLimit"].Value = testFlow.LowerLimit; dgvTestFlow.Rows[index].Cells["Unit"].Value = testFlow.Unit; dgvTestFlow.Rows[index].Cells["SoftBin"].Value = testFlow.SoftBin; dgvTestFlow.Rows[index].Cells["HardBin"].Value = testFlow.HardBin; dgvTestFlow.Rows[index].Cells["Action"].Value = testFlow.Action; } dgvTestFlow.ClearSelection(); //Todo: Delete this later cListTestFlow = oListTestFlow; }
public IInterpreter CallingTraitMethod() { var interpreter = new Interpreter.Interpreter(); foreach (var mutability in Options.AllMutabilityModes) { var env = Environment.Create(new Options() { DebugThrowOnError = true, AllowInvalidMainResult = true }.SetMutability(mutability)); var root_ns = env.Root; root_ns.AddBuilder(TypeBuilder.CreateInterface("ISay") .With(FunctionBuilder.CreateDeclaration("say", ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference()))); root_ns.AddBuilder(TypeBuilder.Create("Say") .With(FunctionBuilder.Create("say", ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(new[] { Return.Create(Int64Literal.Create("2")) })) .SetModifier(EntityModifier.Override)) .Parents("ISay")); root_ns.AddBuilder(TypeBuilder.Create("Greeter", "T")); root_ns.AddBuilder(TypeBuilder.Create("Greeter", "X") .SetModifier(EntityModifier.Trait) .Constraints(ConstraintBuilder.Create("X").Inherits("ISay")) .With(FunctionBuilder.Create("hello", ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement( Return.Create(FunctionCall.Create(NameReference.Create("s", "say"))) )) .Parameters(FunctionParameter.Create("s", NameFactory.ReferenceNameReference("X"))))); root_ns.AddBuilder(FunctionBuilder.Create( "main", ExpressionReadMode.OptionalUse, NameFactory.Int64NameReference(), Block.CreateStatement( VariableDeclaration.CreateStatement("g", null, ExpressionFactory.StackConstructor(NameReference.Create("Greeter", NameReference.Create("Say")))), VariableDeclaration.CreateStatement("y", null, ExpressionFactory.StackConstructor("Say")), Return.Create(FunctionCall.Create(NameReference.Create("g", "hello"), NameReference.Create("y"))) ))); ExecValue result = interpreter.TestRun(env); Assert.AreEqual(2L, result.RetValue.PlainValue); } return(interpreter); }
private static void BuildFNDiagramobject(DbModel model, ReadOnlyCollection <PrimitiveType> storeTypes) { EdmFunctionPayload payload = new EdmFunctionPayload { Schema = "dbo", StoreFunctionName = "fn_diagramobjects", IsComposable = true }; payload.ReturnParameters = new List <FunctionParameter>(); payload.ReturnParameters.Add(FunctionParameter.Create("Value", GetEdmType(model, storeTypes, PrimitiveTypeKind.Int32), ParameterMode.ReturnValue)); EdmFunction function = EdmFunction.Create("fn_diagramobjects", "CodeFirstDatabaseSchema", DataSpace.SSpace, payload, null); model.StoreModel.AddItem(function); }
private void BuildMethod(FunctionDeclaration funcDecl) { string name = funcDecl.Name.Identifier; if (customImplementations.ContainsKey(name)) { stringBuilder.AppendLine(customImplementations[name]); internalCallId++; stringBuilder.AppendLine(); return; } string retType = funcDecl.ReturnType.Declaration; List <string> funcParams = new List <string>(); foreach (FunctionParameter param in funcDecl.Parameters) { string paramType = param.m_Type.Declaration; string paramName = param.m_Lvalue.Identifier; string paramStr = paramType + " " + paramName; if (param is FunctionParameterWithDefault def) { string defaultAsStr = Output_CSharp.GetValueAsString(def.m_Default, false); paramStr += " = " + defaultAsStr; } funcParams.Add(paramStr); } string parameters = funcParams.Count == 0 ? "" : funcParams.Aggregate((a, b) => a + ", " + b); stringBuilder.AppendLine($"{Output_CSharp.GetIndent(2)}public static {retType} {name}({parameters})"); stringBuilder.AppendLine($"{Output_CSharp.GetIndent(2)}{{"); for (int i = funcDecl.Parameters.Count - 1; i >= 0; --i) { FunctionParameter param = funcDecl.Parameters[i]; stringBuilder.AppendLine(Output_CSharp.GetIndent(3) + Output_CSharp.GetStackPush(param.m_Type, param.m_Lvalue, false) + ";"); } stringBuilder.AppendLine(Output_CSharp.GetIndent(3) + Output_CSharp.GetInternalCall(internalCallId++) + ";"); if (funcDecl.ReturnType.GetType() != typeof(VoidType)) { stringBuilder.AppendLine($"{Output_CSharp.GetIndent(3)}return " + Output_CSharp.GetStackPop(funcDecl.ReturnType) + ";"); } stringBuilder.AppendLine($"{Output_CSharp.GetIndent(2)}}}"); stringBuilder.AppendLine(); }
public void Can_create_composable_function_import_with_scalar_collection_result() { DbProviderManifest providerManifest; var containerMapping = GetContainerMapping(out providerManifest); var cTypeUsageString = TypeUsage.CreateDefaultTypeUsage( PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)); var sTypeUsageString = providerManifest.GetStoreType(cTypeUsageString); var rowType = RowType.Create( new[] { EdmProperty.Create("C", sTypeUsageString), }, null); var functionImport = EdmFunction.Create( "F", "N", DataSpace.CSpace, new EdmFunctionPayload { IsComposable = true, ReturnParameters = new[] { FunctionParameter.Create("R", cTypeUsageString.EdmType.GetCollectionType(), ParameterMode.ReturnValue) } }, null); var targetFunction = EdmFunction.Create( "SF", "N", DataSpace.SSpace, new EdmFunctionPayload { IsComposable = true, ReturnParameters = new[] { FunctionParameter.Create("R", rowType.GetCollectionType(), ParameterMode.ReturnValue) } }, null); var resultMapping = new FunctionImportResultMapping(); var functionImportMapping = new FunctionImportMappingComposable( functionImport, targetFunction, resultMapping, containerMapping); Assert.Same(resultMapping, functionImportMapping.ResultMapping); Assert.Null(functionImportMapping.StructuralTypeMappings); Assert.Null(functionImportMapping.TvfKeys); }
public static int ConversionCost(FunctionParameter dest, VariableType src) { if (dest.VarType == src) { return(0); //exact match } if (src?.PropertyType == EPropertyType.Vector && dest.VarType?.PropertyType == EPropertyType.Vector || src?.PropertyType == EPropertyType.Rotator && dest.VarType?.PropertyType == EPropertyType.Rotator) { return(0); } if (dest.VarType is Class c && (src is null || src is ClassType && !c.IsInterface)) { return(0); } if (dest.VarType is DelegateType && src is null) { return(0); } if (dest.IsOut) { return(int.MaxValue); } if (INTERFACE.CaseInsensitiveEquals(dest.VarType?.Name) && src is Class cls && cls.SameAsOrSubClassOf(INTERFACE)) { return(1); //Interface subclass } if (!INTERFACE.CaseInsensitiveEquals(dest.VarType?.Name) && dest.VarType is Class && src is Class) { return(2); } ECast conversion = GetConversion(dest.VarType, src); //if it has 'coerce', any valid conversion is acceptable, otherwise only autoconversions are acceptable if (dest.Flags.Has(UnrealFlags.EPropertyFlags.CoerceParm) ? conversion != ECast.Max : conversion.Has(ECast.AutoConvert)) { if (conversion.Has(ECast.Truncate)) { return(104); //lossy conversion } if (dest.VarType == SymbolTable.FloatType && (src == SymbolTable.IntType || src?.PropertyType == EPropertyType.Byte)) { return(103); //int to float conversion } return(101); //lossless conversion } return(int.MaxValue); }
/// <summary> /// effects: determines if the given function import returns collection type, and if so returns the type /// </summary> internal static bool TryGetFunctionImportReturnCollectionType(EdmFunction functionImport, int resultSetIndex, out CollectionType collectionType) { FunctionParameter returnParameter = GetReturnParameter(functionImport, resultSetIndex); if (returnParameter != null && returnParameter.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType) { collectionType = (CollectionType)returnParameter.TypeUsage.EdmType; return(true); } collectionType = null; return(false); }
public bool VisitNode(FunctionParameter node) { // [specifiers] parametertype parametername[[staticarraysize]] if (node.Specifiers.Count > 0) { Append("{0} ", String.Join(" ", node.Specifiers.Select(x => x.Value))); } String staticarray = node.Variables[0].Size != -1 ? "[" + node.Variables[0].Size + "]" : ""; Append("{0} {1}{2}", node.VarType.Name, node.Name, staticarray); return(true); }
protected internal override void VisitFunctionReturnParameter(FunctionParameter returnParameter) { if (returnParameter.TypeUsage.EdmType.BuiltInTypeKind != BuiltInTypeKind.PrimitiveType) { _schemaWriter.WriteFunctionReturnTypeElementHeader(); base.VisitFunctionReturnParameter(returnParameter); _schemaWriter.WriteEndElement(); } else { base.VisitFunctionReturnParameter(returnParameter); } }
public IErrorReporter ErrorEscapingReceivedReferenceFromFunction() { NameResolver resolver = null; foreach (var mutability in Options.AllMutabilityModes) { var env = Language.Environment.Create(new Options() { DiscardingAnyExpressionDuringTests = true } .SetMutability(mutability)); var root_ns = env.Root; root_ns.AddBuilder(FunctionBuilder.Create("selector", ExpressionReadMode.ReadRequired, NameFactory.ReferenceNameReference(NameFactory.IntNameReference()), Block.CreateStatement( ExpressionFactory.Readout("b"), Return.Create(NameReference.Create("a")) )) .Parameters( FunctionParameter.Create("a", NameFactory.ReferenceNameReference(NameFactory.IntNameReference())), FunctionParameter.Create("b", NameFactory.ReferenceNameReference(NameFactory.IntNameReference())))); FunctionCall call = FunctionCall.Create("selector", IntLiteral.Create("2"), IntLiteral.Create("3")); FunctionDefinition func = root_ns.AddBuilder(FunctionBuilder.Create("notimportant", ExpressionReadMode.OptionalUse, NameFactory.UnitNameReference(), Block.CreateStatement( VariableDeclaration.CreateStatement("h", NameFactory.ReferenceNameReference(NameFactory.IntNameReference()), IntLiteral.Create("0"), EntityModifier.Reassignable), Block.CreateStatement( // error: the most alive reference the function can return is limited to this scope // so it cannot be assigned to outer-scope variable Assignment.CreateStatement(NameReference.Create("h"), call) ), ExpressionFactory.Readout("h") ))); resolver = NameResolver.Create(env); Assert.AreEqual(1, resolver.ErrorManager.Errors.Count); Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.EscapingReference, call)); } return(resolver); }
public object?[] BindFunctionInput(FunctionContext context) { if (_inputBound) { throw new InvalidOperationException("Duplicate binding call detected. " + $"Input parameters can only be bound to arguments once. Use the {nameof(InputArguments)} property to inspect values."); } _parameterValues = new object?[context.FunctionDefinition.Parameters.Length]; _inputBound = true; List <string>?errors = null; for (int i = 0; i < _parameterValues.Length; i++) { FunctionParameter param = context.FunctionDefinition.Parameters[i]; IFunctionBindingsFeature functionBindings = context.GetBindings(); // Check InputData first, then TriggerMetadata if (!functionBindings.InputData.TryGetValue(param.Name, out object?source)) { functionBindings.TriggerMetadata.TryGetValue(param.Name, out source); } var converterContext = new DefaultConverterContext(param, source, context); if (TryConvert(converterContext, out object?target)) { _parameterValues[i] = target; } else if (source is not null) { // Don't initialize this list unless we have to if (errors is null) { errors = new List <string>(); } errors.Add($"Cannot convert input parameter '{param.Name}' to type '{param.Type.FullName}' from type '{source.GetType().FullName}'."); } } // found errors if (errors is not null) { throw new FunctionInputConverterException($"Error converting {errors.Count} input parameters for Function '{context.FunctionDefinition.Name}': {string.Join(Environment.NewLine, errors)}"); } return(_parameterValues); }
public IErrorReporter ErrorHasConstraint() { NameResolver resolver = null; foreach (var mutability in Options.AllMutabilityModes) { var env = Environment.Create(new Options() { AllowInvalidMainResult = true, AllowProtocols = true }.SetMutability(mutability)); var root_ns = env.Root; FunctionDefinition func_constraint = FunctionBuilder.CreateDeclaration("getMe", ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference()); // this function accepts any parameter where parameter type has function "getMe" FunctionDefinition constrained_func = root_ns.AddBuilder(FunctionBuilder.Create("proxy", TemplateParametersBuffer.Create().Add("T").Values, ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(new[] { Return.Create(FunctionCall.Create(NameReference.Create("t", "getMe"))) })) .Constraints(ConstraintBuilder.Create("T").Has(func_constraint)) .Parameters(FunctionParameter.Create("t", NameFactory.PointerNameReference("T")))); // this type does NOT have function "getMe" TypeDefinition type_impl = root_ns.AddBuilder(TypeBuilder.Create("YMan") .With(FunctionBuilder.Create("missing", ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(new[] { Return.Create(Int64Literal.Create("2")) })))); FunctionCall call = FunctionCall.Create(NameReference.Create("proxy"), FunctionArgument.Create(NameReference.Create("y_man"))); root_ns.AddBuilder(FunctionBuilder.Create( "main", ExpressionReadMode.OptionalUse, NameFactory.Int64NameReference(), Block.CreateStatement(new IExpression[] { VariableDeclaration.CreateStatement("y_man", null, ExpressionFactory.HeapConstructor(NameReference.Create("YMan"))), Return.Create(call) }))); resolver = NameResolver.Create(env); Assert.AreEqual(1, resolver.ErrorManager.Errors.Count); Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.ViolatedHasFunctionConstraint, call.Callee)); } return(resolver); }
public IInterpreter OverridingMethodWithIndexerGetter() { var interpreter = new Interpreter.Interpreter(); foreach (var mutability in Options.AllMutabilityModes) { var env = Language.Environment.Create(new Options() { AllowInvalidMainResult = true, DebugThrowOnError = true }.SetMutability(mutability)); var root_ns = env.Root; root_ns.AddBuilder(TypeBuilder.CreateInterface("IProvider") .With(FunctionBuilder.CreateDeclaration(NameFactory.PropertyIndexerName, ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference()) .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference())))); root_ns.AddBuilder(TypeBuilder.Create("Middle") .Parents("IProvider") .SetModifier(EntityModifier.Base) .With(FunctionBuilder.Create(NameFactory.PropertyIndexerName, ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(Return.Create(Int64Literal.Create("500")))) .SetModifier(EntityModifier.Override | EntityModifier.UnchainBase) .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference(), ExpressionReadMode.CannotBeRead)))); root_ns.AddBuilder(TypeBuilder.Create("Last") .Parents("Middle") .SetModifier(EntityModifier.Base) .With(PropertyBuilder.CreateIndexer(env.Options, NameFactory.Int64NameReference()) .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference(), ExpressionReadMode.CannotBeRead)) .With(PropertyMemberBuilder.CreateIndexerGetter(Block.CreateStatement(Return.Create(Int64Literal.Create("2")))) .Modifier(EntityModifier.Override | EntityModifier.UnchainBase)))); root_ns.AddBuilder(FunctionBuilder.Create( "main", ExpressionReadMode.OptionalUse, NameFactory.Int64NameReference(), Block.CreateStatement(new IExpression[] { VariableDeclaration.CreateStatement("p", NameFactory.PointerNameReference("IProvider"), ExpressionFactory.HeapConstructor("Last")), Return.Create(FunctionCall.Create(NameReference.Create("p", NameFactory.PropertyIndexerName), FunctionArgument.Create(Int64Literal.Create("18")))) }))); ExecValue result = interpreter.TestRun(env); Assert.AreEqual(2L, result.RetValue.PlainValue); } return(interpreter); }
public IErrorReporter ErrorEscapingReferenceWithAttachmentObject() { NameResolver resolver = null; foreach (var mutability in Options.AllMutabilityModes) { var env = Language.Environment.Create(new Options() { DiscardingAnyExpressionDuringTests = true } .SetMutability(mutability)); var root_ns = env.Root; root_ns.AddBuilder(TypeBuilder.Create("Keeper") .With(VariableDeclaration.CreateStatement("world", NameFactory.PointerNameReference(NameFactory.IntNameReference()), Undef.Create(), EntityModifier.Public)) .With(FunctionBuilder.CreateInitConstructor(Block.CreateStatement( Assignment.CreateStatement(NameReference.CreateThised("world"), NameReference.Create("in_value")) )) .Parameters(FunctionParameter.Create("in_value", NameFactory.PointerNameReference(NameFactory.IntNameReference()))))); Assignment assign = Assignment.CreateStatement(NameReference.Create("attach"), ExpressionFactory.StackConstructor("Keeper", NameReference.Create("i"))).Cast <Assignment>(); FunctionDefinition func = root_ns.AddBuilder(FunctionBuilder.Create("notimportant", ExpressionReadMode.OptionalUse, NameFactory.UnitNameReference(), Block.CreateStatement( VariableDeclaration.CreateStatement("attach", NameReference.Create("Keeper"), Undef.Create(), EntityModifier.Reassignable), Block.CreateStatement( VariableDeclaration.CreateStatement("i", NameFactory.ReferenceNameReference(NameFactory.IntNameReference()), IntLiteral.Create("0")), // cannot execute this assignment because the reference would move from here to outer scope // just wrapped in `Keeper` instance // please note this `Keeper` instance is attached to `i` // (triggered by conversion reference->pointer in constructor), so it cannot outlive it assign, ExpressionFactory.Readout("attach") ) ))); resolver = NameResolver.Create(env); Assert.AreEqual(1, resolver.ErrorManager.Errors.Count); Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.EscapingReference, assign.RhsValue)); } return(resolver); }
public virtual FunctionParameter RewriteFunctionParameter(FunctionParameter par) { var result = new FunctionParameter(par.Name) { Comment = RewriteComment(par.Comment), DefaultValue = RewriteRaw(par.DefaultValue), ExtraData = RewriteExtraData(par), IsOptional = par.IsOptional, IsRest = par.IsRest, ParameterType = RewriteTypeReference(par.ParameterType), }; return(result); }
protected override void Visit(FunctionParameter functionParameter) { int instanceIndex; if (!this.AddObjectToSeenListAndHashBuilder((object)functionParameter, out instanceIndex)) { return; } this.AddObjectStartDumpToHashBuilder((object)functionParameter, instanceIndex); this.AddObjectContentToHashBuilder((object)functionParameter.Identity); this.AddObjectContentToHashBuilder((object)functionParameter.Mode); base.Visit(functionParameter); this.AddObjectEndDumpToHashBuilder(); }
/// <summary> /// Registers the <see cref="GetPageUriById" /> function. /// </summary> /// <param name="item">The item to apply the convention to.</param> /// <param name="model">The model.</param> private static void RegisterGetPageUriById(EdmModel item, DbModel model) { var idParameter = FunctionParameter.Create( "Id", model.GetStorePrimitiveType(PrimitiveTypeKind.Int32), ParameterMode.In); var returnValue = FunctionParameter.Create( "Result", model.GetStorePrimitiveType(PrimitiveTypeKind.String), ParameterMode.ReturnValue); item.CreateAndAddFunction(GetPageUriByIdFunction, new[] { idParameter }, new[] { returnValue }); }
public IInterpreter HasConstraintWithValue() { var interpreter = new Interpreter.Interpreter(); foreach (var mutability in Options.AllMutabilityModes) { var env = Environment.Create(new Options() { AllowInvalidMainResult = true, AllowProtocols = true, DebugThrowOnError = true }.SetMutability(mutability)); var root_ns = env.Root; FunctionDefinition func_constraint = FunctionBuilder.CreateDeclaration("getMe", ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference()); root_ns.AddBuilder(FunctionBuilder.Create("proxy", TemplateParametersBuffer.Create().Add("T").Values, ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(new[] { Return.Create(FunctionCall.Create(NameReference.Create("t", "getMe"))) })) .Constraints(ConstraintBuilder.Create("T").Has(func_constraint)) .Parameters(FunctionParameter.Create("t", NameReference.Create("T")))); TypeDefinition type_impl = root_ns.AddBuilder(TypeBuilder.Create("Y") .With(FunctionBuilder.Create("getMe", ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(new[] { Return.Create(Int64Literal.Create("2")) })))); FunctionCall call = FunctionCall.Create(NameReference.Create("proxy"), FunctionArgument.Create(NameReference.Create("y"))); root_ns.AddBuilder(FunctionBuilder.Create( "main", ExpressionReadMode.OptionalUse, NameFactory.Int64NameReference(), Block.CreateStatement(new IExpression[] { VariableDeclaration.CreateStatement("y", null, ExpressionFactory.StackConstructor(NameReference.Create("Y"))), Return.Create(call) }))); ExecValue result = interpreter.TestRun(env); Assert.AreEqual(2L, result.RetValue.PlainValue); } return(interpreter); }
public IErrorReporter ErrorAttachmentObjectOnStackAndHeap() { NameResolver resolver = null; foreach (var mutability in Options.AllMutabilityModes) { var env = Language.Environment.Create(new Options() { DiscardingAnyExpressionDuringTests = true } .SetMutability(mutability)); var root_ns = env.Root; root_ns.AddBuilder(TypeBuilder.Create("Keeper") .With(VariableDeclaration.CreateStatement("world", NameFactory.PointerNameReference(NameFactory.IntNameReference()), Undef.Create(), EntityModifier.Public)) .With(FunctionBuilder.CreateInitConstructor(Block.CreateStatement( Assignment.CreateStatement(NameReference.CreateThised("world"), NameReference.Create("in_value")) )) .Parameters(FunctionParameter.Create("in_value", NameFactory.PointerNameReference(NameFactory.IntNameReference()))))); IExpression stack_init_value = ExpressionFactory.StackConstructor("Keeper", NameReference.Create("i")); IExpression heap_init_value = ExpressionFactory.HeapConstructor("Keeper", NameReference.Create("i")); FunctionDefinition func = root_ns.AddBuilder(FunctionBuilder.Create("notimportant", ExpressionReadMode.OptionalUse, NameFactory.UnitNameReference(), Block.CreateStatement( VariableDeclaration.CreateStatement("i", NameFactory.ReferenceNameReference(NameFactory.IntNameReference()), IntLiteral.Create("0"), EntityModifier.Reassignable), // this is incorrect, because we are creating attachment object as value, dropping the lifetime VariableDeclaration.CreateStatement("attach1", NameReference.Create("Keeper"), stack_init_value), ExpressionFactory.Readout("attach1"), // this is incorrect, because we are creating attachment object as global instance, dropping the lifetime VariableDeclaration.CreateStatement("attach2", NameFactory.PointerNameReference(NameReference.Create("Keeper")), heap_init_value), ExpressionFactory.Readout("attach2") ))); resolver = NameResolver.Create(env); Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.EscapingReference, stack_init_value)); Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.EscapingReference, heap_init_value)); Assert.AreEqual(2, resolver.ErrorManager.Errors.Count); } return(resolver); }
public IErrorReporter MethodNoDominance() { // https://en.wikipedia.org/wiki/Dominance_(C%2B%2B)#Example_without_diamond_inheritance NameResolver resolver = null; foreach (var mutability in Options.AllMutabilityModes) { var env = Environment.Create(new Options() { }.SetMutability(mutability)); var root_ns = env.Root; root_ns.AddBuilder(TypeBuilder.Create("Grandparent") .SetModifier(EntityModifier.Base) .With(FunctionBuilder.Create("f", NameFactory.UnitNameReference(), Block.CreateStatement()) .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference(), ExpressionReadMode.CannotBeRead))) .With(FunctionBuilder.Create("f", NameFactory.UnitNameReference(), Block.CreateStatement()) .Parameters(FunctionParameter.Create("a", NameFactory.RealNameReference(), ExpressionReadMode.CannotBeRead), FunctionParameter.Create("b", NameFactory.RealNameReference(), ExpressionReadMode.CannotBeRead)))); root_ns.AddBuilder(TypeBuilder.Create("Parent") .SetModifier(EntityModifier.Base) .Parents("Grandparent") .With(FunctionBuilder.Create("f", NameFactory.UnitNameReference(), Block.CreateStatement()) .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference(), ExpressionReadMode.CannotBeRead)))); root_ns.AddBuilder(TypeBuilder.Create("Child") .Parents("Parent") .With(FunctionBuilder.Create("g", NameFactory.UnitNameReference(), Block.CreateStatement( // unlike C++ this method is seen as regular overload FunctionCall.Create(NameReference.CreateThised("f"), RealLiteral.Create("2.14"), RealLiteral.Create("3.17")))))); resolver = NameResolver.Create(env); Assert.AreEqual(0, resolver.ErrorManager.Errors.Count); } return(resolver); }
private static MethodInfo GetAbsMethod(FunctionParameter param) { PrimitiveType primitive = param.TypeUsage.EdmType as PrimitiveType; if (primitive == null) { return DoubleFunctions.Abs; } Type clrType = primitive.ClrEquivalentType; if (clrType == typeof(decimal)) { return DecimalFunctions.Abs; } else if (clrType == typeof(long)) { return IntegerFunctions.Abs64; } else if (clrType == typeof(int)) { return IntegerFunctions.Abs32; } else if (clrType == typeof(short)) { return IntegerFunctions.Abs16; } else if (clrType == typeof(sbyte)) { return IntegerFunctions.Abs8; } return DoubleFunctions.Abs; }
public FunctionFrame(FunctionFrame original) { Start = original.Start; Returns = original.Returns; Parameters = new List<FunctionParameter> (); foreach (FunctionParameter ofp in original.Parameters) { FunctionParameter copyfp = new FunctionParameter(ofp); Parameters.Add (copyfp); } }
public FunctionParameter(FunctionParameter original) { this.Name = original.Name; this.Type = original.Type; this.TypeDimensions = original.TypeDimensions; }
private FunctionParameter[] ProcessParamList(Notation notation, object p) { List<FunctionParameter> res = new List<FunctionParameter>(); if (p != null) { Symbol[] arr = Lisp.ToArray<Symbol>(p); HashSet<VarName> hs = new HashSet<VarName>(); for (int k = 0; k < arr.Length; k++) { FunctionParameter parameter = new FunctionParameter(); VarName name = (VarName)arr[k]; if (hs.Contains(name)) throw new XQueryException(Properties.Resources.XQST0039, name); hs.Add(name); parameter.id = ProcessVarName(name); Notation.Record[] recs = notation.Select(arr[k], Descriptor.TypeDecl, 1); if (recs.Length > 0) parameter.type = ProcessTypeDecl(notation, recs[0].Arg0); else parameter.type = XQuerySequenceType.Item; res.Add(parameter); } } return res.ToArray(); }
/** * Checks if argument given in the function parameter is known * in the expression. * * @param param the function parameter * * @return true if argument is known, * otherwise returns false. */ private bool checkIfKnownArgument(FunctionParameter param) { if (param.tokens.Count > 1) return false; Token t = param.tokens[0]; if (t.tokenTypeId != Argument.TYPE_ID) return false; return true; }
private static bool IsDecimal(FunctionParameter param) { PrimitiveType primitive = param.TypeUsage.EdmType as PrimitiveType; if (primitive == null) { return false; } return primitive.ClrEquivalentType == typeof(decimal); }
/** * Checks if token is uknown * * @param param the function parameter * * @return true if there is only 1 token with unknown type, * otherwise returns false. */ private bool checkIfUnknownToken(FunctionParameter param) { if (param.tokens.Count > 1) return false; Token t = param.tokens[0]; if (t.tokenTypeId != ConstantValue.NaN) return false; return true; }
private static void LoadFromDisk(IEnumerable<Function> list, nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store) { var folder = Path.Combine(rootFolder, FOLDER_FC); if (!Directory.Exists(folder)) return; #region Load other parameter/field information var fList = Directory.GetFiles(folder, "*.configuration.xml"); foreach (var f in fList) { var document = new XmlDocument(); try { document.Load(f); } catch (Exception ex) { //Do Nothing MessageBox.Show("The file '" + f + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var fi = new FileInfo(f); var name = fi.Name.Substring(0, fi.Name.Length - ".configuration.xml".Length).ToLower(); var itemID = XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.Empty); var item = list.FirstOrDefault(x => x.Id == itemID); if (item == null) { item = new Function(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.NewGuid())) }); model.Functions.Add(item); } System.Windows.Forms.Application.DoEvents(); item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged); item.Name = XmlHelper.GetAttributeValue(document.DocumentElement, "name", item.Name); item.PrecedenceOrder = XmlHelper.GetAttributeValue(document.DocumentElement, "precedenceorder", item.PrecedenceOrder); item.IsGenerated = XmlHelper.GetAttributeValue(document.DocumentElement, "isgenerated", item.IsGenerated); item.CodeFacade = XmlHelper.GetAttributeValue(document.DocumentElement, "codefacade", item.CodeFacade); item.Schema = XmlHelper.GetAttributeValue(document.DocumentElement, "schema", item.Schema); item.IsTable = XmlHelper.GetAttributeValue(document.DocumentElement, "istable", item.IsTable); item.ReturnVariable = XmlHelper.GetAttributeValue(document.DocumentElement, "returnvariable", item.ReturnVariable); item.Summary = XmlHelper.GetNodeValue(document.DocumentElement, "summary", item.Summary); item.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged); //Fields var fieldsNodes = document.DocumentElement.SelectSingleNode("//fieldset"); if (fieldsNodes != null) { var nameList = new List<string>(); foreach (XmlNode n in fieldsNodes.ChildNodes) { var subItemID = XmlHelper.GetAttributeValue(n, "id", Guid.Empty); var field = item.Fields.FirstOrDefault(x => x.Id == subItemID); if (field == null) { field = new FunctionField(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid())) }); item.Fields.Add(field); } field.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged); field.Name = XmlHelper.GetAttributeValue(n, "name", field.Name); field.CodeFacade = XmlHelper.GetAttributeValue(n, "codefacade", field.CodeFacade); nameList.Add(field.Name.ToLower()); field.Nullable = XmlHelper.GetAttributeValue(n, "nullable", field.Nullable); var dtv = XmlHelper.GetAttributeValue(n, "datatype", field.DataType.ToString()); DataTypeConstants dt; if (Enum.TryParse<DataTypeConstants>(dtv, true, out dt)) field.DataType = dt; field.Default = XmlHelper.GetAttributeValue(n, "default", field.Default); field.IsGenerated = XmlHelper.GetAttributeValue(n, "isgenerated", field.IsGenerated); field.Length = XmlHelper.GetAttributeValue(n, "length", field.Length); field.Scale = XmlHelper.GetAttributeValue(n, "scale", field.Scale); field.Summary = XmlHelper.GetNodeValue(n, "summary", field.Summary); field.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged); } if (item.Fields.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0) item.nHydrateModel.IsDirty = true; } //Parameters var parametersNodes = document.DocumentElement.SelectSingleNode("//parameterset"); if (parametersNodes != null) { var nameList = new List<string>(); foreach (XmlNode n in parametersNodes.ChildNodes) { var subItemID = XmlHelper.GetAttributeValue(n, "id", Guid.Empty); var parameter = item.Parameters.FirstOrDefault(x => x.Id == subItemID); if (parameter == null) { parameter = new FunctionParameter(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid())) }); item.Parameters.Add(parameter); } parameter.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged); parameter.CodeFacade = XmlHelper.GetAttributeValue(n, "codefacade", parameter.CodeFacade); parameter.Name = XmlHelper.GetAttributeValue(n, "name", parameter.Name); nameList.Add(parameter.Name.ToLower()); parameter.Nullable = XmlHelper.GetAttributeValue(n, "nullable", parameter.Nullable); var dtv = XmlHelper.GetAttributeValue(n, "datatype", parameter.DataType.ToString()); DataTypeConstants dt; if (Enum.TryParse<DataTypeConstants>(dtv, true, out dt)) parameter.DataType = dt; parameter.Default = XmlHelper.GetAttributeValue(n, "default", parameter.Default); parameter.IsGenerated = XmlHelper.GetAttributeValue(n, "isgenerated", parameter.IsGenerated); parameter.Length = XmlHelper.GetAttributeValue(n, "length", parameter.Length); parameter.Scale = XmlHelper.GetAttributeValue(n, "scale", parameter.Scale); parameter.Summary = XmlHelper.GetNodeValue(n, "summary", parameter.Summary); parameter.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged); } if (item.Parameters.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0) item.nHydrateModel.IsDirty = true; } LoadModules(folder, item); } #endregion #region Load SQL fList = Directory.GetFiles(folder, "*.sql"); foreach (var f in fList) { var fi = new FileInfo(f); if (fi.Name.ToLower().EndsWith(".sql")) { var name = fi.Name.Substring(0, fi.Name.Length - 4).ToLower(); var item = list.FirstOrDefault(x => x.Name.ToLower() == name); if (item != null) { item.SQL = File.ReadAllText(f); System.Windows.Forms.Application.DoEvents(); } } } #endregion }