static void Main() { Console.WriteLine("Enter length"); int length = int.Parse(Console.ReadLine()); GenericArray<string> sentence = new GenericArray<string>(length); //GenericArray<int> array = new GenericArray<int>(length); Console.WriteLine("Elements of GenericArray\r\n{0}", sentence.ToString()); Console.WriteLine("Enter element to add"); sentence.Add(Console.ReadLine()); Console.WriteLine("Elements of GenericArray\r\n{0}", sentence.ToString()); Console.WriteLine("Enter element to insert"); string insertElement = Console.ReadLine(); Console.WriteLine("Enter position"); int insertIndex = int.Parse(Console.ReadLine()); sentence.Insert(insertIndex, insertElement); Console.WriteLine("Elements of GenericArray\r\n{0}", sentence.ToString()); Console.WriteLine("Enter element position to be removed"); int removeIndex = int.Parse(Console.ReadLine()); sentence.Remove(removeIndex); Console.WriteLine("Elements of GenericArray\r\n{0}", sentence.ToString()); Console.WriteLine("Enter element to find"); string findElement = Console.ReadLine(); Console.WriteLine("This element is on position {0}", sentence.Find(findElement)); Console.WriteLine("Enter element position to be printed"); int printIndex = int.Parse(Console.ReadLine()); Console.WriteLine("The element is {0}", sentence[printIndex]); sentence.Clear(); Console.WriteLine("Elements of GenericArray.Clear()\r\n{0}", sentence.ToString()); }
/// <summary> /// Adds certificate extension object identifier (OID) value to a specified extension group. /// </summary> /// <param name="extensionType">Specifies the extension type. Possible values are: <strong>EnabledExtensionList</strong>, <strong>OfflineExtensionList</strong> /// and <strong>DisabledExtensionList</strong>. /// <para>If extension is added, <see cref="IsModified"/> property is set to <strong>True</strong>.</para></param> /// <param name="oid">Certificate extension object identifier.</param> /// <exception cref="ArgumentNullException">The <strong>extensionType</strong> parameter is <strong>Null</strong>.</exception> /// <exception cref="ArgumentException">The <strong>extensionType</strong> parameter value is not valid, or <strong>oid</strong> parameter is invalid /// object identifier.</exception> public void Add(String extensionType, Oid oid) { try { Asn1Utils.EncodeObjectIdentifier(oid); } catch { throw new ArgumentException("Specified object identifier is not valid or is not resolvable"); } if (String.IsNullOrEmpty(extensionType)) { throw new ArgumentNullException(nameof(extensionType)); } List <Oid> existing; switch (extensionType.ToLower()) { case "enabledextensionlist": existing = new List <Oid>(EnabledExtensionList); if (!GenericArray.OidContains(EnabledExtensionList, oid)) { existing.Add(oid); IsModified = true; } EnabledExtensionList = existing.ToArray(); break; case "offlineextensionlist": existing = new List <Oid>(OfflineExtensionList); if (!GenericArray.OidContains(OfflineExtensionList, oid)) { existing.Add(oid); IsModified = true; } OfflineExtensionList = existing.ToArray(); break; case "disabledextensionlist": existing = new List <Oid>(DisabledExtensionList); if (!GenericArray.OidContains(DisabledExtensionList, oid)) { existing.Add(oid); IsModified = true; } DisabledExtensionList = existing.ToArray(); break; default: throw new ArgumentException( "Invalid extension type is specified. Allowed types are: EnabledExtensionList, OfflineExtensionList and DisabledExtensionList."); } }
/// <summary> /// Construct and event signature with the provide parameters by providing a name and an enumerable containing /// <see cref="LSLParameterSignature" /> objects. /// </summary> /// <param name="name">The name of the event signature.</param> /// <param name="parameters">The parameters to include in the signature.</param> /// <exception cref="LSLInvalidSymbolNameException"> /// Thrown if the event handler name does not follow LSL symbol naming conventions. /// </exception> public LSLEventSignature(string name, IEnumerable <LSLParameterSignature> parameters) { Name = name; if (parameters == null) { _parameters = new GenericArray <LSLParameterSignature>(); } else { _parameters = new GenericArray <LSLParameterSignature>(); foreach (var lslParameter in parameters) { AddParameter(lslParameter); } } }
/// <summary> /// Construct a function signature by providing an associated <see cref="LSLType" /> for the return type, a function /// Name and an optional enumerable of <see cref="LSLParameterSignature" /> objects. /// </summary> /// <param name="returnType"></param> /// <param name="name"></param> /// <param name="parameters"></param> /// <exception cref="ArgumentException">Thrown if more than one variadic parameter is added to the function signature.</exception> /// <exception cref="LSLInvalidSymbolNameException"> /// Thrown if the function name does not follow LSL symbol naming conventions. /// </exception> public LSLFunctionSignature(LSLType returnType, string name, IEnumerable <LSLParameterSignature> parameters = null) { ReturnType = returnType; Name = name; VariadicParameterIndex = -1; if (parameters == null) { _parameters = new GenericArray <LSLParameterSignature>(); } else { _parameters = new GenericArray <LSLParameterSignature>(); foreach (var lslParameter in parameters) { AddParameter(lslParameter); } } }
public void SimpleCollectionToArray() { var source = new GenericCollections <int>(false) { List = Enumerable.Range(0, 100).ToList() }; var target = new GenericArray <int>(); var ultraMapper = new Mapper(cfg => { cfg.MapTypes(source, target) .MapMember(a => a.List, b => b.Array); }); ultraMapper.Map(source, target); Assert.IsTrue(source.List.SequenceEqual(target.Array)); }
static Boolean verifycerts(X509Certificate2Collection certs) { if (certs.Count > 0) { String[] issuers = new String[certs.Count]; for (Int32 index = 0; index < certs.Count; index++) { if (certs[index].Handle.Equals(IntPtr.Zero)) { return(false); } issuers[index] = certs[index].Issuer; } if (GenericArray.GetUniques(issuers).Length == 1) { return(true); } } return(false); }
public void SimpleArrayToCollection() { var source = new GenericArray <int>() { Array = Enumerable.Range(0, 100).ToArray() }; //var target = new GenericCollections<int>( true ); var ultraMapper = new Mapper(cfg => { cfg.MapTypes <GenericArray <int>, GenericCollections <int> >() .MapMember(a => a.Array, b => b.List); }); //using existing instance = reuse references //ultraMapper.Map( source, target ); var target = ultraMapper.Map <GenericCollections <int> >(source); Assert.IsTrue(source.Array.SequenceEqual(target.List)); }
/// <summary> /// Create an <see cref="LSLParameterListNode" /> by cloning from another. /// </summary> /// <param name="other">The other node to clone from.</param> /// <exception cref="ArgumentNullException"><paramref name="other" /> is <c>null</c>.</exception> private LSLParameterListNode(LSLParameterListNode other) { if (other == null) { throw new ArgumentNullException("other"); } SourceRangesAvailable = other.SourceRangesAvailable; if (SourceRangesAvailable) { SourceRange = other.SourceRange; _sourceRangeCommaList = other.SourceRangeCommaList.ToGenericArray(); } foreach (var param in other._parameters.Values) { Add(param.Clone()); } HasErrors = other.HasErrors; }
void processCrlNumberExtension() { /* the following rules apply: * 3. if CrlNumberIncrement is greater than zero and there is no CRL Number extension in existing CRL, * CrlNumberIncrement is set as CRL Number extension value. * 4. if CrlNumberIncrement is greater than zero and there is existing CRL Number extension in existing CRL, * CRL Number in existing extension is incremented by CrlNumberIncrement. * 5. if CrlNumberIncrement is zero or negative, no CRL Number extension is added. */ BigInteger newCrlVersion = 0; X509Extension crlNumberExt = _extensions.FirstOrDefault(x => x.Oid.Value == X509CertExtensions.X509CRLNumber); if (crlNumberExt != null) { newCrlVersion = ((X509CRLNumberExtension)crlNumberExt).CRLNumber + CrlNumberIncrement; } if (CrlNumberIncrement > 0) { GenericArray.RemoveExtension(_extensions, X509CertExtensions.X509CRLNumber); crlNumberExt = new X509CRLNumberExtension(newCrlVersion, false); _extensions.Add(crlNumberExt); } }
void generateExtensions(X509Certificate2 issuer) { /* the following rules apply: * 1. remove CA Version and AKI extensions from existing extension list * 2. generate them from issuer certificate. If absent, generate them dynamically. * 3. if CrlNumberIncrement is greater than zero and there is no CRL Number extension in existing CRL, * CrlNumberIncrement is set as CRL Number extension value. * 4. if CrlNumberIncrement is greater than zero and there is existing CRL Number extension in existing CRL, * CRL Number in existing extesnsion is incremented by CrlNumberIncrement. * 5. if CrlNumberIncrement is zero or negative, no CRL Number extension is added. */ GenericArray.RemoveExtension(_extensions, X509CertExtensions.X509AuthorityKeyIdentifier); // AKI generation _extensions.Add(new X509AuthorityKeyIdentifierExtension(issuer, AuthorityKeyIdentifierFlags.KeyIdentifier, false)); GenericArray.RemoveExtension(_extensions, X509CertExtensions.X509CAVersion); // CA Version copy X509Extension e = issuer.Extensions[X509CertExtensions.X509CAVersion]; if (e != null) { _extensions.Add(e); } BigInteger newCrlVersion = 0; X509Extension crlNumberExt = _extensions.FirstOrDefault(x => x.Oid.Value == X509CertExtensions.X509CRLNumber); if (crlNumberExt != null) { newCrlVersion = ((X509CRLNumberExtension)crlNumberExt).CRLNumber + CrlNumberIncrement; } if (CrlNumberIncrement > 0) { GenericArray.RemoveExtension(_extensions, X509CertExtensions.X509CRLNumber); crlNumberExt = new X509CRLNumberExtension(newCrlVersion, false); _extensions.Add(crlNumberExt); } }
public void SimpleToComplexElement() { var source = new GenericCollections <int>(false) { List = Enumerable.Range(0, 100).ToList() }; var target = new GenericArray <InnerType>(); var ultraMapper = new Mapper(cfg => { cfg.MapTypes(source, target) .MapMember(a => a.List, b => b.Array); cfg.MapTypes <int, InnerType>(i => new InnerType() { String = i.ToString() }); }); ultraMapper.Map(source, target); Assert.IsTrue(source.List.Select(inner => inner.ToString()).SequenceEqual( target.Array.Select(item => item.String))); }
private IEnumerable <LSLLibraryFunctionSignature> ModuleMethods(Type containerType) { const BindingFlags bindingFlags = BindingFlags.Default | BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic; if (ScriptModuleConstantAttribute == null) { yield break; } var methods = containerType.GetMethods(bindingFlags) .Where(x => x.GetCustomAttributes(ScriptModuleFunctionAttribute, true).Any()); var subsets = _subsetsMap[containerType]; foreach (var v in methods) { var returnType = LslTypeFromCsharpType(v.ReturnType); var pTypes = new GenericArray <LSLParameterSignature>(); foreach (var p in v.GetParameters().Skip(2)) { var isVariadic = IsParams(p); if (p.ParameterType == (typeof(object[])) && isVariadic) { pTypes.Add(new LSLParameterSignature(LSLType.Void, p.Name, true)); goto omitRestOfParameters; } if (isVariadic) { Log.WriteLineWithHeader("[OpenSimLibraryDataReflector]: ", "Optional script module function {0} of type {1}, variadic parameter {2} is an un-recognized data type ({3}), function omitted", v.Name, containerType.Name, p.Name, p.ParameterType.Name); goto omitFunction; } var type = LslTypeFromCsharpParameterType(p.ParameterType); if (type != null) { pTypes.Add(new LSLParameterSignature(type.Value, p.Name, false)); } else { Log.WriteLineWithHeader("[OpenSimLibraryDataReflector]: ", "Optional script module function {0} of type {1}, parameter {2} is an un-recognized data type ({3}), function omitted", v.Name, containerType.Name, p.Name, p.ParameterType.Name); goto omitFunction; } } omitRestOfParameters: if (returnType != null) { var f = new LSLLibraryFunctionSignature(returnType.Value, v.Name, pTypes); f.DocumentationString = _documentationProvider.DocumentFunction(f); f.Subsets.SetSubsets(subsets); f.ModInvoke = true; yield return(f); } else { Log.WriteLineWithHeader("[OpenSimLibraryDataReflector]: ", "Optional script module {0} of type {1} return type is an un-recognized data type ({2})", v.Name, containerType.Name, v.ReturnType.Name); } omitFunction: ; } }
private IEnumerable <LSLLibraryFunctionSignature> InterfaceMethods(Type containerType) { foreach (var v in containerType.GetMethods()) { var subsets = _subsetsMap[containerType]; var returnType = LslTypeFromCsharpType(v.ReturnType); var pTypes = new GenericArray <LSLParameterSignature>(); foreach (var p in v.GetParameters()) { var isVariadic = IsParams(p); if (p.ParameterType == (typeof(object[])) && isVariadic) { pTypes.Add(new LSLParameterSignature(LSLType.Void, p.Name, true)); goto omitRestOfParameters; } if (isVariadic) { Log.WriteLineWithHeader("[OpenSimLibraryDataReflector]: ", "Interface function {0} of type {1}, variadic parameter {2} is an un-recognized data type ({3}), function omitted", v.Name, containerType.Name, p.Name, p.ParameterType.Name); goto omitFunction; } var type = LslTypeFromCsharpParameterType(p.ParameterType); if (type != null) { pTypes.Add(new LSLParameterSignature(type.Value, p.Name, false)); } else { Log.WriteLineWithHeader("[OpenSimLibraryDataReflector]: ", "Interface function {0} of type {1}, parameter {2} is an un-recognized data type ({3}), function omitted", v.Name, containerType.Name, p.Name, p.ParameterType.Name); goto omitFunction; } } omitRestOfParameters: if (returnType != null) { var f = new LSLLibraryFunctionSignature(returnType.Value, v.Name, pTypes); f.DocumentationString = _documentationProvider.DocumentFunction(f); f.Subsets.SetSubsets(subsets); yield return(f); } else { Log.WriteLineWithHeader("[OpenSimLibraryDataReflector]: ", "function {0} of type {1} return type is an un-recognized data type ({2})", v.Name, containerType.Name, v.ReturnType.Name); } omitFunction: ; } }
private MethodBuilder AddMethodImpl(MethodInfo mi) { var parameters = mi.GetParameters(); var paramTypes = ParamTypes(parameters, false); var mdb = _tb.DefineMethod(mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, paramTypes); if (mi.ContainsGenericParameters) { var ts = mi.GetGenericArguments(); var ss = new string[ts.Length]; for (var i = 0; i < ts.Length; i++) { ss[i] = ts[i].Name; } var genericParameters = mdb.DefineGenericParameters(ss); for (var i = 0; i < genericParameters.Length; i++) { genericParameters[i].SetGenericParameterAttributes(ts[i].GetTypeInfo().GenericParameterAttributes); } } var il = mdb.GetILGenerator(); ParametersArray args = new(il, paramTypes); // object[] args = new object[paramCount]; il.Emit(OpCodes.Nop); var argsArr = new GenericArray <object>(il, ParamTypes(parameters, true).Length); for (var i = 0; i < parameters.Length; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } // object[] packed = new object[PackedArgs.PackedTypes.Length]; GenericArray <object> packedArr = new(il, PackedArgs.PackedTypes.Length); // packed[PackedArgs.DispatchProxyPosition] = this; packedArr.BeginSet(PackedArgs.DispatchProxyPosition); il.Emit(OpCodes.Ldarg_0); packedArr.EndSet(typeof(AspectDispatchProxy)); // packed[PackedArgs.DeclaringTypePosition] = typeof(iface); var Type_GetTypeFromHandle = typeof(Type).GetRuntimeMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }); _assembly.GetTokenForMethod(mi, out var declaringType, out var methodToken); packedArr.BeginSet(PackedArgs.DeclaringTypePosition); il.Emit(OpCodes.Ldtoken, declaringType); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); packedArr.EndSet(typeof(object)); // packed[PackedArgs.MethodTokenPosition] = iface method token; packedArr.BeginSet(PackedArgs.MethodTokenPosition); il.Emit(OpCodes.Ldc_I4, methodToken); packedArr.EndSet(typeof(int)); // packed[PackedArgs.ArgsPosition] = args; packedArr.BeginSet(PackedArgs.ArgsPosition); argsArr.Load(); packedArr.EndSet(typeof(object[])); // packed[PackedArgs.GenericTypesPosition] = mi.GetGenericArguments(); if (mi.ContainsGenericParameters) { packedArr.BeginSet(PackedArgs.GenericTypesPosition); var genericTypes = mi.GetGenericArguments(); GenericArray <Type> typeArr = new(il, genericTypes.Length); for (var i = 0; i < genericTypes.Length; ++i) { typeArr.BeginSet(i); il.Emit(OpCodes.Ldtoken, genericTypes[i]); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); typeArr.EndSet(typeof(Type)); } typeArr.Load(); packedArr.EndSet(typeof(Type[])); } for (var i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType.IsByRef) { args.BeginSet(i); argsArr.Get(i); args.EndSet(i, typeof(object)); } } var invokeMethod = s_delegateInvoke; if (mi.ReturnType == typeof(Task)) { invokeMethod = s_delegateInvokeAsync; } if (IsGenericTask(mi.ReturnType)) { var returnTypes = mi.ReturnType.GetGenericArguments(); invokeMethod = s_delegateinvokeAsyncT.MakeGenericMethod(returnTypes); } // Call AsyncDispatchProxyGenerator.Invoke(object[]), InvokeAsync or InvokeAsyncT il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, _fields[InvokeActionFieldAndCtorParameterIndex]); packedArr.Load(); il.Emit(OpCodes.Callvirt, invokeMethod); if (mi.ReturnType != typeof(void)) { Convert(il, typeof(object), mi.ReturnType, false); } else { il.Emit(OpCodes.Pop); } il.Emit(OpCodes.Ret); _tb.DefineMethodOverride(mdb, mi); return(mdb); }
/// <summary> /// Construct and empty event signature, can only be used by derived classes. /// </summary> protected LSLEventSignature() { _parameters = new GenericArray <LSLParameterSignature>(); }
void AddRpc(TypeDefinition newType, MethodDefinition irpc) { var tag = irpc.CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == "TAG"); if (tag is null) { return; } var cmd = (int)tag.ConstructorArguments.First().Value; var method = new MethodDefinition(irpc.Name, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, irpc.ReturnType); var il = method.Body.GetILProcessor(); var parameters = irpc.Parameters; var paramTypes = ParamTypes(parameters.ToArray(), false); foreach (var param in paramTypes) { method.Parameters.Add(new ParameterDefinition(param)); } if (irpc.ContainsGenericParameter) { throw new Exception($"not have generic parameter{irpc.FullName}"); //var ts = irpc.GenericParameters; //for (int i = 0; i < ts.Count; i++) //{ // method.GenericParameters.Add(ts[i]); //} } ParametersArray args = new ParametersArray(this, il, paramTypes); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldc_I4, cmd); il.Emit(OpCodes.Ldtoken, irpc.ReturnType); var ptype = ModuleDefinition.ImportReference(GetMethodInfo.GetTypeofHandler()); il.Emit(OpCodes.Call, ModuleDefinition.ImportReference(ptype)); GenericArray <System.Object> argsArr = new GenericArray <System.Object>(this, il, ParamTypes(parameters.ToArray(), true).Length); for (int i = 0; i < parameters.Count; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } argsArr.Load(); il.Emit(OpCodes.Call, _methodcall); if (irpc.ReturnType.Name == "Void") { il.Emit(OpCodes.Pop); } else { var res = new VariableDefinition(irpc.ReturnType); method.Body.Variables.Add(res); Convert(il, ModuleDefinition.ImportReference(typeof(System.Object)), irpc.ReturnType, false); il.Emit(OpCodes.Stloc, res); il.Emit(OpCodes.Ldloc, res); } il.Emit(OpCodes.Ret); newType.Methods.Add(method); }
/// <summary> /// Initializes a new instance of the <see cref="LSLFunctionOverloadMatches{T}" /> class with no signature matches at /// all. /// </summary> internal LSLFunctionOverloadMatches() { Matches = new GenericArray <T>(); }
static void Main(string[] args) { try { #region TestUsageOfOperatorOverload Rettangolo A = new Rettangolo(3, 4); Rettangolo B = new Rettangolo(5, 5); Rettangolo C = A + B; Console.WriteLine("Area rettangolo A ({0}x{1}): {2}\nArea rettangolo B ({3}x{4}): {5}\nArea A+B ({6}x{7}): {8}", A.L, A.H, A.GetArea(), B.L, B.H, B.GetArea(), C.L, C.H, C.GetArea()); #endregion #region TestOfUsageOfDelegateFunction Utility.Separatore(); Console.WriteLine("Test di utilizzo di una funzione delegata:"); NumberChanger NC1 = new NumberChanger(TestDelegate.AddNum); NumberChanger NC2 = new NumberChanger(TestDelegate.MultNum); Console.WriteLine("- valore iniziale: {0}", TestDelegate.GetNum()); int plus = 25; NC1(plus); Console.WriteLine("- dopo aggiunta di {0}: {1}", plus, TestDelegate.GetNum()); int multi = 5; NC2(multi); Console.WriteLine("- dopo moltiplicazione per {0}: {1}", multi, TestDelegate.GetNum()); /* resetto il numero */ NC2(0); Console.WriteLine("- dopo aver resettato il numero: {0}", TestDelegate.GetNum()); NumberChanger NC; NC = NC1 + NC2; NC(5); Console.WriteLine("- dopo multicasting (NC = NC1 + NC2): {0}", TestDelegate.GetNum()); Console.WriteLine(); Console.WriteLine("Altro test di utilizzo di un delegato:"); string SDel = "Logga questo"; PrintString PSO = new PrintString(TestDelegateLog.VideoOutput); PrintString PSF = new PrintString(TestDelegateLog.FileOutput); PrintString Log = PSO + PSF; Log(SDel); Console.WriteLine("(la stringa qui sopra è stata mostrata a video e loggata in un file simultaneamente attraverso l'utilizzo di un delegato multicast)"); NumberPrinter NP = delegate(int n) { Console.WriteLine("Altro test: il numero {0} è stato scritto con un delegato anonimo!", n); }; NP(0); NP(1); NP(2); #endregion #region TestOfUsageOfEvents Utility.Separatore(); Console.WriteLine("Test di utilizzo di eventi (con delegati):"); EventTest EV = new EventTest(); EV.OnPrint += EventTest_OnPrint; EV.Print("Uallabalooza"); #endregion #region TestOfUsageOfGenerics Utility.Separatore(); GenericArray <string> SArr = new GenericArray <string>(5); Console.WriteLine("Test di utilizzo dei GENERICS di tipo \"{0}\":", SArr.TypeOf()); SArr.Add(0, "Ualla"); SArr.Add(1, "Balooza"); SArr.Add(2, "In"); SArr.Add(3, "The"); SArr.Add(4, "Sky"); for (var i = 0; i < SArr.Size; i++) { Console.WriteLine("- indice {0}: \"{1}\"", i, SArr.Get(i)); } #endregion #region TestOfUsageOfUnsafeCode /* i puntatori vanno usati solo nei blocchi di codice "unsafe"; * puoi dichiarare unsafe anche una funzione o un metodo, se deve usare puntatori; * occorre permettere la compilazione di codice unsafe dalle impostazioni del progetto */ unsafe { Utility.Separatore(); Console.WriteLine("Test di utilizzo di puntatori in codice UNSAFE:"); int SUns = 12345; int *pSUns = &SUns; Console.WriteLine("- valore: {0}", SUns); Console.WriteLine("- valore da puntatore: {0}", pSUns->ToString()); Console.WriteLine("- indirizzo della variabile: {0}", (int)pSUns); Console.WriteLine(); int SUns2 = 54321; int *pSUns2 = &SUns2; Console.WriteLine("Prima dello SWAP dei due puntatori: {0} - {1}", SUns, SUns2); Swap(pSUns, pSUns2); Console.WriteLine("Dopo lo SWAP dei due puntatori: {0} - {1}", SUns, SUns2); Console.WriteLine(); Console.WriteLine("Test di accesso array con puntatori:"); int[] Arr = new int[] { 10, 20, 30 }; fixed(int *pArr = Arr) for (int i = 0; i < Arr.Length; i++) { Console.WriteLine("- Indirizzo di Arr[{0}]: {1}; Valore di Arr[{0}]: {2}", i, (int)(pArr + i), *(pArr + i)); } } #endregion #region TestOfUsageOfThreads Utility.Separatore(); Console.WriteLine("Test di utilizzo dei THREAD"); Thread TH = Thread.CurrentThread; TH.Name = "ThreadMain"; Console.WriteLine("Nome del thread corrente: {0}", TH.Name); ThreadStart TS = new ThreadStart(ThreadSingolo); Console.WriteLine("Creazione in corso di un thread figlio..."); Thread Child = new Thread(TS); Child.Start(); int SleepTime = 5000; Console.WriteLine("Metto in pausa per {0} secondi...", SleepTime / 1000); Thread.Sleep(SleepTime); Console.WriteLine("Riprendo l'esecuzione!"); /*Console.WriteLine("Esco dall'esecuzione del thread (metodo Abort())..."); * Child.Abort();*/ /* non usare Child.Abort! usa Child.Interrupt quando è in stato di sleep-wait-join */ #endregion } #region catch /*catch(ThreadAbortException e) * { * Console.WriteLine("Thread distrutto! (metodo Abort())"); * }*/ catch (Exception e) { Utility.MostraEccezione <Exception>(e); } #endregion Console.ReadKey(); }
/// <summary> /// Construct an empty <see cref="LSLFunctionSignature" />. Only derived classes can do this. /// </summary> protected LSLFunctionSignature() { ReturnType = LSLType.Void; _parameters = new GenericArray <LSLParameterSignature>(); VariadicParameterIndex = -1; }
public OpenSimLibraryReflectedTypeData(string openSimBinDirectory) { _openSimBinDirectory = openSimBinDirectory; foreach (var assemblyPath in Directory.EnumerateFiles(openSimBinDirectory, "*.dll", SearchOption.AllDirectories)) { try { string assemblyName = Path.GetFileName(assemblyPath); if (assemblyName != null && !_allOpenSimAssemblies.ContainsKey(assemblyName)) { _allOpenSimAssemblies.Add(assemblyName, Assembly.LoadFrom(assemblyPath)); } } catch { //this is sparta } } ScriptApiAssembly = _allOpenSimAssemblies["OpenSim.Region.ScriptEngine.Shared.dll"]; ScriptRuntimeAssembly = _allOpenSimAssemblies["OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"]; RegionFrameworkAssembly = _allOpenSimAssemblies["OpenSim.Region.Framework.dll"]; OpenMetaverseTypesAssembly = _allOpenSimAssemblies["OpenMetaverseTypes.dll"]; ScriptModuleFunctionAttribute = RegionFrameworkAssembly.GetType("OpenSim.Region.Framework.Interfaces.ScriptInvocationAttribute"); ScriptModuleConstantAttribute = RegionFrameworkAssembly.GetType("OpenSim.Region.Framework.Interfaces.ScriptConstantAttribute"); AppDomain.CurrentDomain.AssemblyResolve += _currentDomainOnAssemblyResolve; _eventNames = new HashedSet <string>( ScriptRuntimeAssembly.GetType("OpenSim.Region.ScriptEngine.Shared.ScriptBase.Executor") .GetNestedType("scriptEvents") .GetMembers(BindingFlags.Public | BindingFlags.Static) .Where(x => x.Name != "None") .Select(x => x.Name) ); foreach (var assembly in AllOpenSimAssemblies.Values) { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; try { var types = assembly.GetTypes(); var interfaces = types.Where(x => x.GetInterfaces().Any(y => y.Name == "INonSharedRegionModule")); _scriptModuleClasses.AddRange( interfaces.Where(t => t.GetFields(bindingFlags).Cast <MemberInfo>().Concat(t.GetMethods(bindingFlags)) .Any(h => h.GetCustomAttributes(true).Any( x => { var n = x.GetType().Name; return(n == "ScriptConstantAttribute" || n == "ScriptInvocationAttribute"); }))).ToList() ); } catch (ReflectionTypeLoadException e) { Log.WriteLineWithHeader("[OpenSimLibraryReflector ASSEMBLY LOAD EXCEPTION]", string.Join(Environment.NewLine, e.LoaderExceptions.Select(x => x.Message))); } } FunctionContainingInterfaces = ScriptApiAssembly.GetTypes() .Where(x => x.IsInterface && x.Namespace == "OpenSim.Region.ScriptEngine.Shared.Api.Interfaces") .ToList(); ScriptBaseClass = ScriptRuntimeAssembly.GetType("OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass"); ScriptConstantContainerClasses = new GenericArray <Type> { ScriptBaseClass }; AppDomain.CurrentDomain.AssemblyResolve -= _currentDomainOnAssemblyResolve; }
private static CSharpClassNameValidationResult _Validate(string input, ClassSigType signatureType, bool allowBuiltinAliases, CSharpParsedTypeValidateTypeCallback validateTypeCallback, int index) { if (input == null) { throw new ArgumentNullException("input", "Class name/signature string cannot be null!"); } if (string.IsNullOrWhiteSpace(input)) { return(new CSharpClassNameValidationResult { Success = false, ErrorDescription = "Class name/signature cannot be whitespace.", ErrorIndex = index, }); } string fullyQualifiedName = ""; var genericArgs = new GenericArray <CSharpClassNameValidationResult>(); var qualifications = new GenericArray <Qualification>() { new Qualification(new StringBuilder(), index) }; string genericPart = ""; bool isGeneric = false; int genericBrackets = 0; foreach (var c in input) { //enter generic arguments if (c == '<') { isGeneric = true; genericBrackets++; } //check if we have gotten to the generic part of the type signature yet (if any) if (!isGeneric) { if (c == '.') { //qualifier operator is not allowed anywhere in declaration signatures because //they only consist of a raw type name and generic argument specifications if (signatureType == ClassSigType.Declaration) { return(new CSharpClassNameValidationResult { Success = false, ErrorDescription = string.Format( "'.' name qualifier operator is not valid in a class declaration/generic " + "type placeholder name."), ErrorIndex = index, }); } //detect a missing qualifier section that's terminated with a dot. if (string.IsNullOrWhiteSpace(qualifications.Last().ToString())) { return(new CSharpClassNameValidationResult { Success = false, ErrorDescription = "\'..\' is an invalid use of the qualification operator.", ErrorIndex = index, }); } qualifications.Add(new Qualification(new StringBuilder(), index + 1)); } else { qualifications.Last().Builder.Append(c); } } if (genericBrackets == 0 && !isGeneric) { //accumulate to our fully qualified name fullyQualifiedName += c; } else if (genericBrackets == 0 && isGeneric) { //we have exited even pairs of brackets and are on the //other side of the generic arguments at the end of the signature //there should not be anything here return(new CSharpClassNameValidationResult { Success = false, ErrorDescription = "extra content found after generic argument list.", ErrorIndex = index }); } else if (!(genericBrackets == 1 && c == '<')) { //passed the start of the first < in the signature by 1 if ((c == ',' || c == '>') && genericBrackets == 1) { //we have accumulated a type argument suitable for recursive decent //validate it recursively var validateGenericArgument = _Validate(genericPart.Trim(), signatureType, allowBuiltinAliases, validateTypeCallback, index - genericPart.Length); //return immediately on failure if (!validateGenericArgument.Success) { return(validateGenericArgument); } //add the validated 'tree' genericArgs.Add(validateGenericArgument); //reset the accumulator genericPart = ""; } else { //accumulate until we hit a comma or the > character genericPart += c; } } if (c == '>') { //exit a generic type scope genericBrackets--; } index++; } if (genericBrackets > 0) { //something is amiss with bracket matching return(new CSharpClassNameValidationResult { Success = false, ErrorDescription = "mismatched generic type brackets.", ErrorIndex = index }); } //there may be only one qualification, in which case //the base name is also the fully qualified name. var baseName = qualifications.Last(); if (qualifications.Count > 1) { //uses qualified names, this is definitely an initialization signature //because the qualifier '.' operator returns an error in declaration signatures //above the recursive call to validate foreach (var name in qualifications) { if (string.IsNullOrWhiteSpace(name.Builder.ToString())) { return(new CSharpClassNameValidationResult { Success = false, ErrorDescription = string.Format("qualified type name '{0}' is incomplete.", fullyQualifiedName), ErrorIndex = name.StartIndex }); } } foreach (var name in qualifications) { //check for syntax errors in the qualified name pieces, they need to be valid ID's and not keywords //IsValidIdentifier takes care of both these criteria if (!CSharpIDValidator.IsValidIdentifier(name.Builder.ToString())) { //sound something funky return(new CSharpClassNameValidationResult { Success = false, ErrorDescription = string.Format( "'{0}' is not valid in the given qualified type name '{1}'.", name.Builder, fullyQualifiedName), ErrorIndex = name.StartIndex }); } } } else { var shortName = baseName.Builder.ToString(); //single type argument to a generic type if (string.IsNullOrWhiteSpace(shortName)) { return(new CSharpClassNameValidationResult { Success = false, ErrorDescription = string.Format("missing generic {0} name.", signatureType == ClassSigType.Initialization ? "type argument" : "placeholder type"), ErrorIndex = baseName.StartIndex, }); } bool aliasInitialization = allowBuiltinAliases && CSharpKeywords.BuiltInTypeMap.ContainsKey(shortName) && signatureType == ClassSigType.Initialization; if (!aliasInitialization && !CSharpIDValidator.IsValidIdentifier(baseName.Builder.ToString())) { return(new CSharpClassNameValidationResult { Success = false, ErrorDescription = string.Format("'{0}' is not an allowed CSharp identifier.", baseName.Builder), ErrorIndex = baseName.StartIndex }); } } var baseNameString = baseName.Builder.ToString(); if (isGeneric && CSharpKeywords.IsTypeAliasKeyword(fullyQualifiedName)) { return(new CSharpClassNameValidationResult { Success = false, ErrorDescription = string.Format("Built in type alias '{0}' is not a generic type.", baseName.Builder), ErrorIndex = baseName.StartIndex }); } //success var classDescription = new CSharpClassNameValidationResult() { QualifiedName = fullyQualifiedName, BaseName = baseNameString, GenericArguments = genericArgs, IsGeneric = isGeneric, Success = true }; if (isGeneric) { classDescription.FullSignature = fullyQualifiedName + "<" + string.Join(", ", classDescription.GenericArguments.Select(x => x.FullSignature)) + ">"; } else { classDescription.FullSignature = fullyQualifiedName; } if (validateTypeCallback == null || signatureType != ClassSigType.Initialization) { return(classDescription); } var typeCheckResult = validateTypeCallback(classDescription); if (typeCheckResult.IsValid) { return(classDescription); } classDescription.FullSignature = null; classDescription.ErrorIndex = qualifications.First().StartIndex; classDescription.ErrorDescription = typeCheckResult.ErrorMessage; classDescription.Success = false; return(classDescription); }
/// <summary> /// Validates the specified constructor signature string. /// It expects a constructor signature string which starts at the first parenthesis after the constructor's name /// identifier. /// </summary> /// <param name="input">The constructor signature string.</param> /// <param name="validateTypeCallback"> /// The validate type callback, used for additional custom validation of parameter types /// in the constructor signature. /// </param> /// <returns>A parse/validation results object. <see cref="CSharpConstructorSignatureValidationResult" /></returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="input" /> is <c>null</c>.</exception> public static CSharpConstructorSignatureValidationResult Validate(string input, CSharpParsedTypeValidateTypeCallback validateTypeCallback = null) { if (input == null) { throw new ArgumentNullException("input", "Constructor signature string cannot be null!"); } var result = new CSharpConstructorSignatureValidationResult { Success = true, ParameterForwarding = CSharpConstructorParameterForwarding.None }; if (string.IsNullOrWhiteSpace(input)) { result.Success = false; result.ErrorDescription = "Constructor signature cannot be whitespace."; return(result); } States state = States.Start; string accum = ""; var parameterTypes = new GenericArray <CSharpClassNameValidationResult>(); var parameterNames = new HashSet <string>(); var forwardedParameters = new GenericArray <string>(); int unclosedGenericsBrackets = 0; //weeeeeeeeeeeeeeee! for (int index = 0; index < input.Length; index++) { var c = input[index]; accum += c; if (c == '(') { switch (state) { case States.Start: state = States.WaitingForParamType; accum = ""; continue; case States.AccumulatingForwardingKeyword: switch (accum) { case "base(": result.ParameterForwarding = CSharpConstructorParameterForwarding.Base; break; case "this(": result.ParameterForwarding = CSharpConstructorParameterForwarding.This; break; default: result.Success = false; result.ErrorDescription = "Constructor forwarding keyword must be 'base' or 'this'."; result.ErrorIndex = index - 5; return(result); } accum = ""; state = States.WaitingForForwardedParam; continue; case States.AfterForwardingKeyword: state = States.WaitingForForwardedParam; accum = ""; continue; default: result.Success = false; result.ErrorDescription = "Unexpected opening parenthesis."; result.ErrorIndex = index; return(result); } } if (c == ':') { if (state == States.EndOfBasicSignature) { accum = ""; state = States.WaitingForForwardingKeyword; continue; } result.Success = false; result.ErrorDescription = "CSharpIDValidator.IsValidIdentifier:' character."; result.ErrorIndex = index; return(result); } if (c == '<') { if (state == States.AccumulatingParamType) { unclosedGenericsBrackets++; state = States.AccumulatingGenericType; continue; } if (state == States.AccumulatingGenericType) { unclosedGenericsBrackets++; continue; } result.Success = false; result.ErrorDescription = "CSharpIDValidator.IsValidIdentifier<' character."; result.ErrorIndex = index; return(result); } if (c == '>') { if (state == States.AccumulatingGenericType) { unclosedGenericsBrackets--; if (unclosedGenericsBrackets == 0) { state = States.AccumulatingParamType; } continue; } result.Success = false; result.ErrorDescription = "CSharpIDValidator.IsValidIdentifier>' character."; result.ErrorIndex = index; return(result); } if (c == ',' || c == ')') { switch (state) { case States.WaitingForParamType: if (parameterTypes.Count > 0 || (parameterTypes.Count == 0 && c == ',')) { result.Success = false; result.ErrorDescription = "Missing parameter declaration."; result.ErrorIndex = index - 1; return(result); } accum = ""; state = States.EndOfBasicSignature; continue; case States.WaitingForForwardedParam: if (forwardedParameters.Count > 0 || (forwardedParameters.Count == 0 && c == ',')) { result.Success = false; result.ErrorDescription = "Missing forwarded argument declaration."; result.ErrorIndex = index; return(result); } accum = ""; state = States.EndOfForwardingSignature; continue; case States.AccumulatingParamType: result.Success = false; result.ErrorDescription = "Missing parameter name."; result.ErrorIndex = index; return(result); case States.AccumulatingParamName: { var pname = accum.TrimEnd(',', ')').Trim(); if (!CSharpIDValidator.IsValidIdentifier(pname)) { result.Success = false; result.ErrorDescription = string.Format("Invalid parameter name '{0}'.", pname); result.ErrorIndex = index - accum.Length; return(result); } if (!parameterNames.Contains(pname)) { parameterNames.Add(pname); } else { result.Success = false; result.ErrorDescription = string.Format("Parameter name '{0}' used more than once.", pname); result.ErrorIndex = index - accum.Length; return(result); } accum = ""; state = c == ',' ? States.WaitingForParamType : States.EndOfBasicSignature; continue; } case States.AccumulatingForwardedParam: { var pname = accum.TrimEnd(',', ')').Trim(); if (!CSharpIDValidator.IsValidIdentifier(pname)) { result.Success = false; result.ErrorDescription = string.Format( "Invalid forwarded parameter '{0}', invalid identifier syntax.", pname); result.ErrorIndex = index - accum.Length; return(result); } if (!parameterNames.Contains(pname)) { result.Success = false; result.ErrorDescription = string.Format( "Invalid forwarded parameter '{0}', name was not previously declared.", pname); result.ErrorIndex = index - accum.Length; return(result); } forwardedParameters.Add(pname); accum = ""; state = c == ',' ? States.WaitingForForwardedParam : States.EndOfForwardingSignature; continue; } default: if (c == ',' && state == States.AccumulatingGenericType) { continue; } result.Success = false; result.ErrorDescription = string.Format( "CSharpIDValidator.IsValidIdentifier{0}' character.", c); result.ErrorIndex = index; return(result); } } if (!char.IsWhiteSpace(c)) { switch (state) { case States.EndOfBasicSignature: case States.EndOfForwardingSignature: result.Success = false; result.ErrorDescription = string.Format("Unexpected character '{0}' after signature.", c); result.ErrorIndex = index; return(result); case States.Start: result.Success = false; result.ErrorDescription = string.Format("Unexpected character '{0}', was expecting '('.", c); result.ErrorIndex = index; return(result); case States.WaitingForParamType: state = States.AccumulatingParamType; accum = "" + c; continue; case States.WaitingForParameterName: state = States.AccumulatingParamName; accum = "" + c; continue; case States.WaitingForForwardingKeyword: state = States.AccumulatingForwardingKeyword; accum = "" + c; continue; case States.WaitingForForwardedParam: state = States.AccumulatingForwardedParam; accum = "" + c; continue; } } if (char.IsWhiteSpace(c)) { switch (state) { case States.WaitingForParamType: case States.WaitingForParameterName: case States.EndOfBasicSignature: case States.WaitingForForwardingKeyword: case States.AfterForwardingKeyword: case States.WaitingForForwardedParam: accum = ""; continue; case States.AccumulatingForwardingKeyword: switch (accum) { case "base ": result.ParameterForwarding = CSharpConstructorParameterForwarding.Base; break; case "this ": result.ParameterForwarding = CSharpConstructorParameterForwarding.This; break; default: result.Success = false; result.ErrorDescription = "Constructor forwarding keyword must be 'base' or 'this'."; result.ErrorIndex = index - 5; return(result); } accum = ""; state = States.AfterForwardingKeyword; continue; case States.AccumulatingParamType: var ptype = accum.TrimEnd(); var validateParameter = CSharpClassNameValidator.ValidateInitialization(accum.TrimEnd(), true, validateTypeCallback); if (!validateParameter.Success) { result.Success = false; result.ErrorDescription = string.Format("Invalid parameter type '{0}': {1}", ptype, validateParameter.ErrorDescription); result.ErrorIndex = (index - accum.Length) + validateParameter.ErrorIndex + 1; return(result); } parameterTypes.Add(validateParameter); state = States.WaitingForParameterName; accum = ""; continue; } } } if (state != States.EndOfBasicSignature && state != States.EndOfForwardingSignature) { result.Success = false; result.ErrorDescription = "Incomplete constructor signature."; result.ErrorIndex = input.Length - 1; return(result); } result.ParameterTypes = parameterTypes; result.ParameterNames = parameterNames.ToGenericArray(); result.ForwardedParameters = forwardedParameters; return(result); }
void AddRpc(TypeDefinition newType, MethodDefinition irpc) { var tag = irpc.CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == "TAG"); if (tag is null) { return; } var cmdx = tag.ConstructorArguments.First().Value; var cmd = 0; switch (cmdx) { case Mono.Cecil.CustomAttributeArgument args: cmd = (int)args.Value; break; default: cmd = (int)cmdx; break; } var method = new MethodDefinition(irpc.Name, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, irpc.ReturnType); var il = method.Body.GetILProcessor(); var parameters = irpc.Parameters; var paramTypes = ParamTypes(parameters.ToArray(), false); for (int i = 0; i < paramTypes.Length; i++) { method.Parameters.Add(new ParameterDefinition(parameters[i].Name, parameters[i].Attributes, paramTypes[i])); } if (irpc.ContainsGenericParameter) { throw new Exception($"not have generic parameter{irpc.FullName}"); } var returntype = irpc.ReturnType; if (returntype.IsGenericInstance) { var genreturntype = returntype as GenericInstanceType; if (genreturntype.Name != "Task`1") { throw new Exception($"return type error:{genreturntype.FullName}"); } if (genreturntype.GenericArguments[0].Name == "IResult") { ParametersArray args = new ParametersArray(this, il, paramTypes); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, obj); il.Emit(OpCodes.Ldc_I4, cmd); GenericArray <object> argsArr = new GenericArray <object>(this, il, ParamTypes(parameters.ToArray(), true).Length); for (int i = 0; i < parameters.Count; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } argsArr.Load(); var asyncAction = obj.FieldType.Resolve().Methods.First(p => p.Name == "AsyncFunc"); il.Emit(OpCodes.Callvirt, ModuleDefinition.ImportReference(asyncAction)); il.Emit(OpCodes.Ret); newType.Methods.Add(method); } else { ParametersArray args = new ParametersArray(this, il, paramTypes); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, obj); il.Emit(OpCodes.Ldc_I4, cmd); GenericArray <object> argsArr = new GenericArray <object>(this, il, ParamTypes(parameters.ToArray(), true).Length); for (int i = 0; i < parameters.Count; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } argsArr.Load(); var genericAsyncFunc = obj.FieldType.Resolve().Methods.First(p => p.Name == "AsyncFunc" && p.CallingConvention == MethodCallingConvention.Generic); il.Emit(OpCodes.Callvirt, ModuleDefinition.ImportReference(MakeGenericInstanceMethod(genericAsyncFunc, genreturntype.GenericArguments.ToArray()))); il.Emit(OpCodes.Ret); newType.Methods.Add(method); } } else if (returntype.FullName == "System.Void") { ParametersArray args = new ParametersArray(this, il, paramTypes); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, obj); il.Emit(OpCodes.Ldc_I4, cmd); GenericArray <object> argsArr = new GenericArray <object>(this, il, ParamTypes(parameters.ToArray(), true).Length); for (int i = 0; i < parameters.Count; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } argsArr.Load(); var Action = obj.FieldType.Resolve().Methods.First(p => p.Name == "Action"); il.Emit(OpCodes.Callvirt, ModuleDefinition.ImportReference(Action)); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ret); newType.Methods.Add(method); } else if (returntype.FullName == "System.Threading.Tasks.Task") { ParametersArray args = new ParametersArray(this, il, paramTypes); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, obj); il.Emit(OpCodes.Ldc_I4, cmd); GenericArray <object> argsArr = new GenericArray <object>(this, il, ParamTypes(parameters.ToArray(), true).Length); for (int i = 0; i < parameters.Count; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } argsArr.Load(); var asyncAction = obj.FieldType.Resolve().Methods.First(p => p.Name == "AsyncAction"); il.Emit(OpCodes.Callvirt, ModuleDefinition.ImportReference(asyncAction)); il.Emit(OpCodes.Ret); newType.Methods.Add(method); } else { ParametersArray args = new ParametersArray(this, il, paramTypes); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, obj); il.Emit(OpCodes.Ldc_I4, cmd); il.Emit(OpCodes.Ldtoken, irpc.ReturnType); var ptype = ModuleDefinition.ImportReference(GetMethodInfo.GetTypeofHandler()); il.Emit(OpCodes.Call, ptype); GenericArray <object> argsArr = new GenericArray <object>(this, il, ParamTypes(parameters.ToArray(), true).Length); for (int i = 0; i < parameters.Count; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } argsArr.Load(); var func = obj.FieldType.Resolve().Methods.First(p => p.Name == "Func"); il.Emit(OpCodes.Callvirt, ModuleDefinition.ImportReference(func)); var res = new VariableDefinition(irpc.ReturnType); method.Body.Variables.Add(res); Convert(il, ModuleDefinition.ImportReference(typeof(object)), irpc.ReturnType, false); il.Emit(OpCodes.Stloc, res); il.Emit(OpCodes.Ldloc, res); il.Emit(OpCodes.Ret); newType.Methods.Add(method); } }
/// <summary> /// Construct an event signature that has no parameters by providing a name only. /// </summary> /// <param name="name">The name of the event signature.</param> /// <exception cref="LSLInvalidSymbolNameException"> /// Thrown if the event handler name does not follow LSL symbol naming conventions. /// </exception> protected LSLEventSignature(string name) { Name = name; _parameters = new GenericArray <LSLParameterSignature>(); }
private void AddMethodImpl(MethodInfo mi) { ParameterInfo[] parameters = mi.GetParameters(); Type[] paramTypes = ParamTypes(parameters, false); MethodBuilder mdb = _tb.DefineMethod(mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, paramTypes); if (mi.ContainsGenericParameters) { Type[] ts = mi.GetGenericArguments(); string[] ss = new string[ts.Length]; for (int i = 0; i < ts.Length; i++) { ss[i] = ts[i].Name; } GenericTypeParameterBuilder[] genericParameters = mdb.DefineGenericParameters(ss); for (int i = 0; i < genericParameters.Length; i++) { genericParameters[i].SetGenericParameterAttributes(ts[i].GetTypeInfo().GenericParameterAttributes); } } ILGenerator il = mdb.GetILGenerator(); ParametersArray args = new ParametersArray(il, paramTypes); // object[] args = new object[paramCount]; il.Emit(OpCodes.Nop); GenericArray <object> argsArr = new GenericArray <object>(il, ParamTypes(parameters, true).Length); for (int i = 0; i < parameters.Length; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } // object[] packed = new object[PackedArgs.PackedTypes.Length]; GenericArray <object> packedArr = new GenericArray <object>(il, PackedArgs.PackedTypes.Length); // packed[PackedArgs.DispatchProxyPosition] = this; packedArr.BeginSet(PackedArgs.DispatchProxyPosition); il.Emit(OpCodes.Ldarg_0); packedArr.EndSet(typeof(DispatchProxy)); // packed[PackedArgs.DeclaringTypePosition] = typeof(iface); MethodInfo Type_GetTypeFromHandle = typeof(Type).GetRuntimeMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }); _assembly.GetTokenForMethod(mi, out Type declaringType, out int methodToken); packedArr.BeginSet(PackedArgs.DeclaringTypePosition); il.Emit(OpCodes.Ldtoken, declaringType); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); packedArr.EndSet(typeof(object)); // packed[PackedArgs.MethodTokenPosition] = iface method token; packedArr.BeginSet(PackedArgs.MethodTokenPosition); il.Emit(OpCodes.Ldc_I4, methodToken); packedArr.EndSet(typeof(Int32)); // packed[PackedArgs.ArgsPosition] = args; packedArr.BeginSet(PackedArgs.ArgsPosition); argsArr.Load(); packedArr.EndSet(typeof(object[])); // packed[PackedArgs.GenericTypesPosition] = mi.GetGenericArguments(); if (mi.ContainsGenericParameters) { packedArr.BeginSet(PackedArgs.GenericTypesPosition); Type[] genericTypes = mi.GetGenericArguments(); GenericArray <Type> typeArr = new GenericArray <Type>(il, genericTypes.Length); for (int i = 0; i < genericTypes.Length; ++i) { typeArr.BeginSet(i); il.Emit(OpCodes.Ldtoken, genericTypes[i]); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); typeArr.EndSet(typeof(Type)); } typeArr.Load(); packedArr.EndSet(typeof(Type[])); } // Call static DispatchProxyHelper.Invoke(object[]) il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, _fields[InvokeActionFieldAndCtorParameterIndex]); // delegate packedArr.Load(); il.Emit(OpCodes.Call, s_delegateInvoke); for (int i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType.IsByRef) { args.BeginSet(i); argsArr.Get(i); args.EndSet(i, typeof(object)); } } if (mi.ReturnType != typeof(void)) { packedArr.Get(PackedArgs.ReturnValuePosition); Convert(il, typeof(object), mi.ReturnType, false); } il.Emit(OpCodes.Ret); _tb.DefineMethodOverride(mdb, mi); }
/// <summary> /// Parses and validates a string as a CSharp method call. /// </summary> /// <param name="signature">The method call signature, without a semi-colon at the end.</param> /// <returns>A parse/validation results object. <see cref="CSharpFunctionCallValidationResult" /></returns> /// <exception cref="ArgumentNullException"><paramref name="signature"/> is <c>null</c>.</exception> public static CSharpFunctionCallValidationResult Validate(string signature) { if (signature == null) { throw new ArgumentNullException("signature"); } var result = new CSharpFunctionCallValidationResult { Success = true }; var explicitGenericParameters = new GenericArray <CSharpClassNameValidationResult>(); var parameters = new GenericArray <CSharpParameterSignature>(); var lastModifier = CSharpParameterModifier.None; var state = States.WaitingForFirstCharacter; var stateBeforeBrackets = new Stack <States>(); var stateBeforeGenericTypePart = new Stack <States>(); var stateBeforeParenthesis = new Stack <States>(); var stateBeforeCurlyBraces = new Stack <States>(); string accum = ""; int unmatchedGenericBrackets = 0; int unmatchedParenthesis = 0; int unmatchedCurlyBraces = 0; int unmatchedBrackets = 0; string methodName = ""; for (int index = 0; index < signature.Length; index++) { var c = signature[index]; accum += c; if (c == 'o' || c == 'r' || c == 'n') { int wordBoundry = index + 2; int ahead = wordBoundry + 1; if (wordBoundry >= signature.Length) { goto afterRefOutChecks; } var lookAhead = signature.Substring(index, 3); var lookAheadAssertion = lookAhead == "out" || lookAhead == "ref" || lookAhead == "new"; if (ahead < signature.Length && !char.IsWhiteSpace(signature[ahead])) { goto afterRefOutChecks; } if (lookAheadAssertion && state == States.WaitingForParameterName && lastModifier == CSharpParameterModifier.None) { lastModifier = lookAhead == "out" ? CSharpParameterModifier.Out : (lookAhead == "ref" ? CSharpParameterModifier.Ref : CSharpParameterModifier.New); accum = ""; index = wordBoundry; state = States.WaitingForParameterName; continue; } } afterRefOutChecks: if (c == '[') { if (state == States.AccumulatingParameter || state == States.WaitingForParameterName) { stateBeforeBrackets.Push(States.AccumulatingParameter); state = States.InBracketExpression; unmatchedBrackets++; continue; } if (state == States.InBracketExpression || state == States.InCurlyBraceExpression || state == States.InParenthesizedExpression) { unmatchedBrackets++; continue; } } if (c == ']') { if (state == States.InBracketExpression || state == States.InCurlyBraceExpression || state == States.InParenthesizedExpression) { unmatchedBrackets--; if (unmatchedBrackets < 0) { result.Success = false; result.ErrorDescription = "Unexpected closing bracket."; result.ErrorIndex = index; return(result); } if (unmatchedBrackets == 0) { if (stateBeforeBrackets.Count > 0) { state = stateBeforeBrackets.Pop(); } else if (state == States.InBracketExpression) { goto unexpectedBracket; } } continue; unexpectedBracket: result.Success = false; result.ErrorDescription = "Unexpected closing bracket."; result.ErrorIndex = index; return(result); } } if (c == '{') { if (state == States.AccumulatingParameter || state == States.WaitingForParameterName) { stateBeforeCurlyBraces.Push(States.AccumulatingParameter); state = States.InCurlyBraceExpression; unmatchedCurlyBraces++; continue; } if (state == States.InBracketExpression || state == States.InCurlyBraceExpression || state == States.InParenthesizedExpression) { unmatchedCurlyBraces++; continue; } } if (c == '}') { if (state == States.InBracketExpression || state == States.InCurlyBraceExpression || state == States.InParenthesizedExpression) { unmatchedCurlyBraces--; if (unmatchedCurlyBraces < 0) { result.Success = false; result.ErrorDescription = "Unexpected closing brace."; result.ErrorIndex = index; return(result); } if (unmatchedCurlyBraces == 0) { if (stateBeforeCurlyBraces.Count > 0) { state = stateBeforeCurlyBraces.Pop(); } else if (state == States.InCurlyBraceExpression) { goto unexpectedCurlyBrace; } } continue; } unexpectedCurlyBrace: result.Success = false; result.ErrorDescription = "Unexpected closing brace."; result.ErrorIndex = index; return(result); } if (c == ')') { if (state == States.WaitingForParameterName && parameters.Count == 0) { if (lastModifier == CSharpParameterModifier.None) { state = States.AfterSignature; accum = ""; } //otherwise the signature is incomplete continue; } if (state == States.InBracketExpression || state == States.InCurlyBraceExpression || state == States.InParenthesizedExpression) { unmatchedParenthesis--; if (unmatchedParenthesis < 0) { result.Success = false; result.ErrorDescription = "Unexpected closing parenthesis."; result.ErrorIndex = index; return(result); } if (unmatchedParenthesis == 0) { if (stateBeforeParenthesis.Count > 0) { state = stateBeforeParenthesis.Pop(); } else if (state == States.InParenthesizedExpression) { goto unexpectedParenth; } } continue; } if (state == States.AccumulatingParameter) { var param = accum.Substring(0, accum.Length - 1).Trim(); if (!CSharpIDValidator.IsValidIdentifier(param) && (lastModifier == CSharpParameterModifier.Ref || lastModifier == CSharpParameterModifier.Out)) { result.Success = false; result.ErrorDescription = "'ref' and 'out' can only be used with a direct variable reference."; result.ErrorIndex = index - (accum.Length - 1); return(result); } string err; int errIndex; if (lastModifier == CSharpParameterModifier.New && !IsValidNewParameter(param, index - (accum.Length - 1), out err, out errIndex)) { result.Success = false; result.ErrorDescription = err; result.ErrorIndex = errIndex; return(result); } if (lastModifier == CSharpParameterModifier.None && !IsValidPlainParameter(param, index - (accum.Length - 1), out err, out errIndex)) { result.Success = false; result.ErrorDescription = err; result.ErrorIndex = errIndex; return(result); } parameters.Add(new CSharpParameterSignature(param, lastModifier)); accum = ""; lastModifier = CSharpParameterModifier.None; state = States.AfterSignature; continue; } unexpectedParenth: result.Success = false; result.ErrorDescription = "Unexpected closing parenthesis."; result.ErrorIndex = index; return(result); } if (c == '(') { if (state == States.AccumulatingParameter || state == States.WaitingForParameterName) { stateBeforeParenthesis.Push(States.AccumulatingParameter); state = States.InParenthesizedExpression; unmatchedParenthesis++; continue; } if (state == States.AfterExplicitGenericMethodParameters) { accum = ""; state = States.WaitingForParameterName; continue; } if (state == States.AccumulatingMethodNamePart) { methodName = accum.TrimEnd('(').Trim(); accum = ""; state = States.WaitingForParameterName; continue; } if (state == States.InBracketExpression || state == States.InCurlyBraceExpression || state == States.InParenthesizedExpression) { unmatchedParenthesis++; continue; } result.Success = false; result.ErrorDescription = "Unexpected opening parenthesis."; result.ErrorIndex = index; return(result); } if (c == ',') { if (state == States.InBracketExpression || state == States.InCurlyBraceExpression || state == States.InParenthesizedExpression) { continue; } if (state == States.AccumulatingExplicitGenericMethodParameters) { var param = accum.TrimEnd(',').Trim(); var validate = CSharpClassNameValidator.ValidateInitialization(param, true); if (!validate.Success) { result.Success = false; result.ErrorDescription = validate.ErrorDescription; result.ErrorIndex = (index - (accum.Length - 1)) + validate.ErrorIndex; return(result); } explicitGenericParameters.Add(validate); accum = ""; continue; } if (state == States.AccumulatingParameter) { var param = accum.TrimEnd(',').Trim(); if (!CSharpIDValidator.IsValidIdentifier(param) && (lastModifier == CSharpParameterModifier.Ref || lastModifier == CSharpParameterModifier.Out)) { result.Success = false; result.ErrorDescription = "'ref' and 'out' can only be used with a direct variable reference."; result.ErrorIndex = index - (accum.Length - 1); return(result); } string err; int errIndex; if (lastModifier == CSharpParameterModifier.New && !IsValidNewParameter(param, index - (accum.Length - 1), out err, out errIndex)) { result.Success = false; result.ErrorDescription = err; result.ErrorIndex = errIndex; return(result); } if (lastModifier == CSharpParameterModifier.None && !IsValidPlainParameter(param, index - (accum.Length - 1), out err, out errIndex)) { result.Success = false; result.ErrorDescription = err; result.ErrorIndex = errIndex; return(result); } state = States.WaitingForParameterName; parameters.Add(new CSharpParameterSignature(param, lastModifier)); lastModifier = CSharpParameterModifier.None; accum = ""; continue; } result.Success = false; result.ErrorDescription = "Unexpected ',' character."; result.ErrorIndex = index; return(result); } if (c == '<') { if (state == States.AccumulatingParameter || state == States.InCurlyBraceExpression || state == States.InParenthesizedExpression || state == States.InBracketExpression) { continue; } if (state == States.AccumulatingMethodNamePart) { methodName = accum.TrimEnd('<').Trim(); accum = ""; state = States.AccumulatingExplicitGenericMethodParameters; continue; } if (state == States.AccumulatingExplicitGenericMethodParameters) { unmatchedGenericBrackets++; stateBeforeGenericTypePart.Push(state); state = States.AccumulatingGenericTypePart; continue; } if (state == States.AccumulatingGenericTypePart) { unmatchedGenericBrackets++; continue; } result.Success = false; result.ErrorDescription = "Unexpected '<' character."; result.ErrorIndex = index; return(result); } if (c == '>') { if (state == States.AccumulatingParameter || state == States.InCurlyBraceExpression || state == States.InParenthesizedExpression || state == States.InBracketExpression) { continue; } if (state == States.AccumulatingGenericTypePart) { unmatchedGenericBrackets--; if (unmatchedGenericBrackets == 0) { state = stateBeforeGenericTypePart.Pop(); } continue; } if (state == States.AccumulatingExplicitGenericMethodParameters) { var param = accum.Substring(0, accum.Length > 0 ? accum.Length - 1 : 0).Trim(); var validate = CSharpClassNameValidator.ValidateInitialization(param, true); if (!validate.Success) { result.Success = false; result.ErrorDescription = validate.ErrorDescription; result.ErrorIndex = (index - (accum.Length - 1)) + validate.ErrorIndex; return(result); } explicitGenericParameters.Add(validate); accum = ""; state = States.AfterExplicitGenericMethodParameters; continue; } result.Success = false; result.ErrorDescription = "Unexpected '>' character."; result.ErrorIndex = index; return(result); } if (!char.IsWhiteSpace(c)) { if (state == States.AccumulatingParameter || state == States.AccumulatingExplicitGenericMethodParameters || state == States.AccumulatingMethodNamePart || state == States.AccumulatingGenericTypePart || state == States.InCurlyBraceExpression || state == States.InBracketExpression || state == States.InParenthesizedExpression) { continue; } if (state == States.WaitingForParameterName) { accum = "" + c; state = States.AccumulatingParameter; continue; } if (state == States.WaitingForFirstCharacter) { accum = "" + c; state = States.AccumulatingMethodNamePart; continue; } result.Success = false; result.ErrorDescription = string.Format("Unexpected '{0}' character.", c); result.ErrorIndex = index; return(result); } } if (state != States.AfterSignature) { result.Success = false; result.ErrorDescription = "Call signature incomplete."; result.ErrorIndex = signature.Length - 1; return(result); } result.MethodName = methodName; result.Parameters = parameters; result.ExplicitGenericParameters = explicitGenericParameters; return(result); }
/// <summary> /// Validates/parses the specified CSharp inheritance list given in <paramref name="input" />. /// The parser supports 'where' type constraints on generic parameters. /// The signature given should be the source content immediately after a classes declared name, without the separating /// colon if there is one. /// </summary> /// <param name="input">The inheritance list signature to parse.</param> /// <returns>A parse/validation results object. <see cref="CSharpInheritanceListValidationResult" /></returns> /// <exception cref="ArgumentNullException"><paramref name="input"/> is <c>null</c>.</exception> public static CSharpInheritanceListValidationResult Validate(string input) { if (input == null) { throw new ArgumentNullException("input"); } var result = new CSharpInheritanceListValidationResult(); var compareValidatedType = new EquateValidatedTypes(); var inheritedTypes = new HashSet <CSharpClassNameValidationResult>(compareValidatedType); var constrainedTypeParameters = new HashSet <string>(); var typeConstraints = new GenericArray <HashSet <CSharpTypeConstraintValidationResult> >(); result.Success = true; States state = States.WaitingForFirstWord; States stateBeforeGenericPart = 0; string accum = ""; int unmatchedGenericBraces = 0; for (int index = 0; index < input.Length; index++) { var c = input[index]; bool end = index == input.Length - 1; accum += c; if (end) { if (state == States.AccumulatingInheritedType || state == States.AfterFirstInheritedType || state == States.AccumulatingFirstWord || state == States.WaitingForFirstWord || (state == States.AccumulatingGenericPart && (stateBeforeGenericPart == States.AccumulatingInheritedType || stateBeforeGenericPart == States.AccumulatingFirstWord))) { var word = accum.Trim(); CSharpClassNameValidationResult init; string err; if (!IsValidInheritedType(word, out err, out init)) { result.ErrorDescription = err; result.ErrorIndex = (index - (accum.Length - 1)) + (init == null ? 0 : init.ErrorIndex); result.Success = false; return(result); } if (!inheritedTypes.Add(init)) { result.ErrorDescription = string.Format("Type '{0}' cannot be inherited more than once.", init.FullSignature); result.ErrorIndex = (index - (accum.Length - 1)) + (init.ErrorIndex); result.Success = false; return(result); } state = States.EndOfListWithoutWhereClauses; continue; } if (state == States.AccumulatingTypeConstraint || state == States.AfterConstraintColon || (state == States.AccumulatingGenericPart && (stateBeforeGenericPart == States.AccumulatingTypeConstraint))) { var word = accum.Trim(); string err; CSharpTypeConstraintValidationResult init; if (!IsValidTypeConstraint(word, out err, out init)) { result.ErrorDescription = err; result.ErrorIndex = (index - (accum.Length - 1)); result.Success = false; return(result); } if (!typeConstraints.Last().Add(init)) { result.ErrorDescription = string.Format( "Type constraint '{0}' cannot be used more than once for generic parameter '{1}'.", init.ConstraintString, constrainedTypeParameters.Last()); result.ErrorIndex = (index - (accum.Length - 1)); result.Success = false; return(result); } state = States.EndOfListWithWhereClauses; continue; } } if (c == '<') { if (state == States.AccumulatingFirstWord || state == States.AccumulatingTypeConstraint || state == States.AccumulatingInheritedType) { stateBeforeGenericPart = state; state = States.AccumulatingGenericPart; unmatchedGenericBraces++; continue; } if (state == States.AccumulatingGenericPart) { unmatchedGenericBraces++; continue; } result.ErrorDescription = string.Format("Unexpected character '{0}'.", c); result.ErrorIndex = index; result.Success = false; return(result); } if (c == '>') { if (state == States.AccumulatingGenericPart) { unmatchedGenericBraces--; if (unmatchedGenericBraces == 0) { state = stateBeforeGenericPart; } continue; } result.ErrorDescription = string.Format("Unexpected character '{0}'.", c); result.ErrorIndex = index; result.Success = false; return(result); } if (c == ',') { if ((state == States.AfterWhereKeyword && inheritedTypes.Count > 0) || state == States.AccumulatingConstraintParam) { result.ErrorDescription = string.Format("Unexpected character '{0}'.", c); result.ErrorIndex = index; result.Success = false; return(result); } if (state == States.AccumulatingTypeConstraint) { var word = accum.TrimEnd(',').Trim(); string err; CSharpTypeConstraintValidationResult init; if (!IsValidTypeConstraint(word, out err, out init)) { result.ErrorDescription = err; result.ErrorIndex = (index - (accum.Length - 1)); result.Success = false; return(result); } if (!typeConstraints.Last().Add(init)) { result.ErrorDescription = string.Format( "Type constraint '{0}' cannot be used more than once for generic parameter '{1}'.", init.ConstraintString, constrainedTypeParameters.Last()); result.ErrorIndex = (index - (accum.Length - 1)); result.Success = false; return(result); } accum = ""; continue; } if (state == States.AccumulatingInheritedType || state == States.AccumulatingFirstWord || (state == States.AfterWhereKeyword && inheritedTypes.Count == 0)) { var type = accum.TrimEnd(',').Trim(); CSharpClassNameValidationResult init; string err; if (!IsValidInheritedType(type, out err, out init)) { result.ErrorDescription = err; result.ErrorIndex = (index - (accum.Length - 1)); result.Success = false; return(result); } if (!inheritedTypes.Add(init)) { result.ErrorDescription = string.Format( "Type '{0}' cannot be inherited more than once.", init.FullSignature); result.ErrorIndex = (index - (accum.Length - 1)); result.Success = false; return(result); } accum = ""; state = States.AfterFirstInheritedType; continue; } } if (c == 'w') { var ahead = index + 5; if (ahead > input.Length) { goto pastWhereCheck; } var lookAheadAsertion = input.Substring(index, 5) == "where"; var lookBehindsertion = index == 0 || char.IsWhiteSpace(input[index - 1]); if (lookAheadAsertion && lookBehindsertion) { if (ahead < input.Length && !char.IsWhiteSpace(input[ahead]) && input[ahead] != ',') { goto pastWhereCheck; } if (state == States.WaitingForFirstWord) { accum = ""; index += 4; state = States.AfterWhereKeyword; //there is an ambiguous case here because you can inherit a class named where, before a where clause occurs if (index + 1 == input.Length) { inheritedTypes.Add(CSharpClassNameValidator.ValidateInitialization("where", false)); state = States.EndOfListWithoutWhereClauses; continue; } bool haveWhitespace = false; for (int i = index + 1; i < input.Length; i++) { var cr = input[i]; if (char.IsWhiteSpace(cr)) { haveWhitespace = true; if (i == input.Length - 1) { inheritedTypes.Add(CSharpClassNameValidator.ValidateInitialization("where", false)); state = States.EndOfListWithoutWhereClauses; break; } continue; } if (cr == 'w' && haveWhitespace) { ahead = i + 5; if (ahead > input.Length) { continue; } lookAheadAsertion = input.Substring(i, 5) == "where"; if (lookAheadAsertion) { if (ahead < input.Length && !char.IsWhiteSpace(input[ahead]) && input[ahead] != ',') { continue; } inheritedTypes.Add(CSharpClassNameValidator.ValidateInitialization("where", false)); index = i + 4; state = States.AfterWhereKeyword; break; } } if (cr == ',') { inheritedTypes.Add(CSharpClassNameValidator.ValidateInitialization("where", false)); index = i; state = States.AccumulatingInheritedType; } break; } continue; } if (state == States.AccumulatingTypeConstraint) { var word = accum.TrimEnd('w').Trim(); string err; CSharpTypeConstraintValidationResult init; if (!IsValidTypeConstraint(word, out err, out init)) { result.ErrorDescription = err; result.ErrorIndex = (index - (accum.Length - 1)); result.Success = false; return(result); } if (!typeConstraints.Last().Add(init)) { result.ErrorDescription = string.Format( "Type constraint '{0}' cannot be used more than once for generic parameter '{1}'.", init.ConstraintString, constrainedTypeParameters.Last()); result.ErrorIndex = (index - (accum.Length - 1)); result.Success = false; return(result); } accum = ""; index += 4; state = States.AfterWhereKeyword; continue; } if (state == States.AccumulatingInheritedType || state == States.AccumulatingFirstWord) { var word = accum.TrimEnd('w').Trim(); CSharpClassNameValidationResult init; string err; if (!IsValidInheritedType(word, out err, out init)) { result.ErrorDescription = err; result.ErrorIndex = (index - (accum.Length - 1)) + (init == null ? 0 : init.ErrorIndex); result.Success = false; return(result); } if (!inheritedTypes.Add(init)) { result.ErrorDescription = string.Format("Type '{0}' cannot be inherited more than once.", init.FullSignature); result.ErrorIndex = (index - (accum.Length - 1)) + (init.ErrorIndex); result.Success = false; return(result); } state = States.AfterWhereKeyword; accum = ""; index += 4; continue; } } } pastWhereCheck: if (c == ':') { if (state == States.AfterWhereKeyword) { result.ErrorDescription = string.Format("Unexpected character '{0}'.", c); result.ErrorIndex = index; result.Success = false; return(result); } if (state == States.AccumulatingConstraintParam) { var constrainedType = accum.TrimEnd(':').Trim(); if (!CSharpIDValidator.IsValidIdentifier(constrainedType)) { result.ErrorDescription = string.Format("Invalid generic type constraint name '{0}'.", constrainedType); result.ErrorIndex = (index - (accum.Length - 1)); result.Success = false; return(result); } if (!constrainedTypeParameters.Add(constrainedType)) { result.ErrorDescription = string.Format( "Generic parameter '{0}' cannot have more than one type constraint list.", constrainedType); result.ErrorIndex = (index - (accum.Length - 1)); result.Success = false; return(result); } typeConstraints.Add(new HashSet <CSharpTypeConstraintValidationResult>()); accum = ""; state = States.AfterConstraintColon; continue; } } if (!char.IsWhiteSpace(c)) { switch (state) { case States.AfterWhereKeyword: accum = "" + c; state = States.AccumulatingConstraintParam; continue; case States.WaitingForFirstWord: accum = "" + c; state = States.AccumulatingFirstWord; continue; case States.AfterFirstInheritedType: accum = "" + c; state = States.AccumulatingInheritedType; continue; case States.AfterConstraintColon: accum = "" + c; state = States.AccumulatingTypeConstraint; continue; } } if (!char.IsWhiteSpace(c)) { continue; } switch (state) { case States.AfterConstraintColon: accum = ""; continue; case States.WaitingForFirstWord: accum = ""; continue; case States.AfterFirstInheritedType: accum = ""; continue; case States.AfterWhereKeyword: accum = ""; break; } } if (state != States.EndOfListWithoutWhereClauses && state != States.EndOfListWithWhereClauses && state != States.WaitingForFirstWord) { result.Success = false; result.ErrorDescription = "Class inheritance list is incomplete."; result.ErrorIndex = input.Length; return(result); } result.ConstrainedTypeParameters = constrainedTypeParameters.ToGenericArray(); result.InheritedTypes = inheritedTypes.ToGenericArray(); result.ParameterConstraints = typeConstraints.Select(x => x.ToGenericArray()).ToGenericArray(); result.Fullsignature = ""; if (result.InheritedTypes.Count > 0) { result.Fullsignature += string.Join(", ", result.InheritedTypes.Select(x => x.FullSignature)); if (result.ConstrainedTypeParameters.Count > 0) { result.Fullsignature += " "; } } result.Fullsignature += string.Join(" ", result.ConstrainedTypeParameters.Select( (x, i) => "where " + result.ConstrainedTypeParameters[i] + " : " + string.Join(", ", result.ParameterConstraints[i].Select(c => c.ConstraintString)))); return(result); }
/// <summary> /// Initializes a new instance of the <see cref="LSLFunctionOverloadMatches{T}" /> class with a single un-ambiguous /// signature match. /// </summary> /// <param name="match">The match.</param> internal LSLFunctionOverloadMatches(T match) { Matches = new GenericArray <T> { match }; }
static void Main(string[] args) { // Permutations of an array. int[] arr = new int[] { 0, 3, 2, 1, 4, 9, 6, 7, 8, 5 }; int[] res = new int[arr.Length]; bool[] used = new bool[arr.Length]; Permutations.PermuteArr(arr, res, used, 0, 0); //Permutations.PermuteArr(new List<int>(arr), 0); // Combinations of array. Console.Out.WriteLine("Now combinations"); string str = "abcd"; List <string> combntns = Combinations.CominateArr(str, str.Length); foreach (string st in combntns) { Console.Out.WriteLine(st); } GenericArray <int> .MergeSort(arr, 0, arr.Length - 1); int[,] mat = new int[, ] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 11 }, { 9, 20, 100 } }; Tuple <int, int> searchIndex = ArraysStrings.ElementSearch2D(mat, 20, 0, mat.GetLength(0) - 1, 0, mat.GetLength(1) - 1); int[,] binary = new int[, ] { { 0, 1, 1, 0, 1 }, { 1, 1, 0, 1, 0 }, { 0, 1, 1, 1, 0 }, { 1, 1, 1, 1, 0 }, { 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0 } }; int max1s = ArraysStrings.MaxSubmatrixOfOnes(binary); // Don't run this with large arrays. // Configurations.PrintConfigurations(arr, 0, res); StringBuilder paths = new StringBuilder(); ArraysStrings.ListAllPaths(2, 2, paths); // Binary Search Trees. Node n1 = new Node(null, null, 1); Node n4 = new Node(null, null, 4); Node n3 = new Node(n1, n4, 3); Node n7 = new Node(null, null, 7); Node n12 = new Node(null, null, 12); Node n10 = new Node(n7, n12, 10); Node n5 = new Node(n3, n10, 5); // Arrays and strings. String testStr = "apple"; double[,] input = new double[, ] { { 1, 9 }, { 15, 20 } }; // ArraysStrings.CumulativeSum(input); double[,] optimals = ArraysStrings.OptimalPath(input); char[] inputChars = "apple".ToCharArray(); ArraysStrings.removeDuplicates(inputChars); // Data structures. Stack <Node> stk = new Stack <Node>(); Queue <Node> qu = new Queue <Node>(); Dictionary <string, int> dict = new Dictionary <string, int>(); SortedDictionary <string, int> sdict = new SortedDictionary <string, int>(); List <int> lst = new List <int>(); Console.Read(); }