public ScriptErrorLogger SetupViewer(string script) { List <string> AllAddedNames = new List <string>(); CodeBlocks.Clear(); Script newscript = new Script(); newscript.Analyse(script); if (newscript.Logger.hasErrors()) { return(newscript.Logger); } foreach (ICodeStruct codeStruct in newscript.Code) { Assignation item = (Assignation)codeStruct; CodeElement element = new CodeElement { Occurence = AllAddedNames.Count(n => n == item.Assignee), Name = item.Assignee }; CodeBlock block = item.Value as CodeBlock; element.Childrens = block != null?RunInBlock(block, AllAddedNames) : new List <CodeElement>(); AllAddedNames.Add(element.Name); CodeBlocks.Add(element); } OnPropertyChanged("CodeBlocks"); return(null); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Title,Block,Langue,Function,PostedDate,ModifiedDate")] CodeBlocks codeBlocks) { if (id != codeBlocks.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(codeBlocks); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CodeBlocksExists(codeBlocks.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(codeBlocks)); }
public void AddSetter() { this.propertyDefinition.SetMethod = new MethodDefinition("set_" + this.Name, this.propertyDefinition.GetMethod.Attributes, this.moduleDefinition.TypeSystem.Void); this.propertyDefinition.SetMethod.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, this.ReturnType.typeReference)); this.type.typeDefinition.Methods.Add(this.propertyDefinition.SetMethod); this.Setter = new Method(this.type, this.propertyDefinition.SetMethod); this.Setter.NewCoder().SetValue(this.BackingField, CodeBlocks.GetParameter(0)).Return().Replace(); }
public async Task <IActionResult> Create([Bind("Id,Title,Block,Langue,Function,PostedDate,ModifiedDate")] CodeBlocks codeBlocks) { if (ModelState.IsValid) { _context.Add(codeBlocks); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(codeBlocks)); }
public void SetCodeBlocks(List <VisualizerHelper.CodeBlock> list) { Clear(); CodeBlocks.Clear(); ILOffsetsByLine.Clear(); foreach (var item in list) { AppendText(item); } }
internal CecilatorBase(CecilatorBase builderBase) { this.Initialize(builderBase); this.moduleDefinition = builderBase.moduleDefinition; this.ReferencedAssemblies = builderBase.ReferencedAssemblies; this.allTypes = builderBase.allTypes; this.ResourceNames = builderBase.ResourceNames; this.Identification = CodeBlocks.GenerateName(); }
private void setCode(ICodeStruct internalScript) { CodeBlocks.Clear(); EditorScript = internalScript == null? "" : internalScript.Parse(null, 0); List <AssignationModel> listBlock = ModelsToScriptHelper. TransformScriptToModels(managedScript, new RelayCommand <object>(DeleteNode)); foreach (AssignationModel item in listBlock) { CodeBlocks.Add(item); } }
public void SaveScript() { if (SelectedTabIndex == "Scripter") { managedScript = ModelsToScriptHelper.TransformModelsToScript(CodeBlocks.ToList()); } else if (SelectedTabIndex == "Editor") { ManagedScript.Analyse(editorScript); } codeBlocks.Clear(); Messenger.Default.Send(new NotificationMessage("HideScripter")); }
public VisualizerHelper.CodeBlock CodeBlockAt(Place place) { var index = CodeBlocks.BinarySearch(new VisualizerHelper.CodeBlock() { Start = place, End = place }); if (index >= 0) { return(CodeBlocks[index]); } return(null); }
public void SaveScript() { //Make sure all syntax exceptions are ignored, we'll show them later switch (Configurator.getScripterPreference()) { case "Scripter": managedScript = ModelsToScriptHelper.TransformModelsToScript(CodeBlocks.ToList()); break; case "Editor": ManagedScript.Analyse(editorScript); break; } CodeBlocks.Clear(); Close(); }
private void AppendText(VisualizerHelper.CodeBlock block) { var oldPlace = new Place(GetLineLength(LinesCount - 1), LinesCount - 1); if (block is VisualizerHelper.InstructionOpCodeCodeBlock) { AppendText(block.Text, boldStyle); } else if (block is VisualizerHelper.TypeCodeBlock) { AppendText(block.Text, typeTealStyle); } else if (block is VisualizerHelper.MemberCodeBlock) { AppendText(block.Text, linkStyle); } else if (block is VisualizerHelper.InstructionOffsetCodeBlock) { if (((VisualizerHelper.InstructionOffsetCodeBlock)block).IsTarget) { AppendText(block.Text, redlinkStyle); } else { AppendText(block.Text, GrayStyle); } } else { // todo apply styles AppendText(block.Text); } //if descriptor contains some additional data ... //save descriptor in sorted list block.Start = oldPlace; block.End = new Place(GetLineLength(LinesCount - 1), LinesCount - 1); if (block is VisualizerHelper.InstructionOffsetCodeBlock && !((VisualizerHelper.InstructionOffsetCodeBlock)block).IsTarget) { ILOffsetsByLine[block.Start.iLine] = (int)block.Tag; } CodeBlocks.Add(block); }
public void SetupViewer(string script) { CodeBlocks.Clear(); Script newscript = new Script(); newscript.Analyse(script); foreach (CodeStructures.Assignation item in newscript.Code) { CodeElement element = new CodeElement(); element.Line = item.Line; element.Name = item.Assignee; if (item.Value is CodeBlock) { element.Childrens = RunInBlock(item.Value as CodeBlock); } else { element.Childrens = new List <CodeElement>(); } CodeBlocks.Add(element); } OnPropertyChanged("CodeBlocks"); }
public void DeleteNode(object sender) { if (!(sender is AssignationModel)) { return; } AssignationModel model = (AssignationModel)sender; foreach (AssignationModel child in CodeBlocks.ToList()) { //If it is the same as the searched one if (child == sender) { //Remove CodeBlocks.Remove(child); } else { //loop inside DeleteInChilds(child, model); } } }
private static Method CreateAssigningMethod(Builder builder, BuilderType anonSource, BuilderType anonTarget, BuilderType anonTargetInterface, Method method) { var name = $"<{counter++}>f__Anon_Assign"; var assignMethod = method.OriginType.CreateMethod(Modifiers.PrivateStatic, anonTarget, name, anonSource); assignMethod.NewCoder() .Context(context => { var resultVar = context.GetOrCreateReturnVariable(); context.SetValue(resultVar, x => x.NewObj(anonTarget.ParameterlessContructor)); foreach (var property in anonSource.Properties) { try { var targetProperty = anonTarget.GetProperty(property.Name); if (property.ReturnType.Fullname != targetProperty.ReturnType.Fullname) { builder.Log(LogTypes.Error, property, $"The property '{property.Name}' does not have the expected return type. Is: {property.ReturnType.Fullname} Expected: {targetProperty.ReturnType.Fullname}"); continue; } context.Load(resultVar).Call(targetProperty.Setter, x => x.Load(CodeBlocks.GetParameter(0)).Call(property.Getter)); } catch (MethodNotFoundException) { builder.Log(LogTypes.Warning, anonTarget, $"The property '{property.Name}' does not exist in '{anonTarget.Name}'"); } } return(context.Load(resultVar).Return()); }) .Replace(); assignMethod.CustomAttributes.AddEditorBrowsableAttribute(EditorBrowsableState.Never); return(assignMethod); }
private static void CreatePropertySetterDelegate(Builder builder, PropertyBuilderInfo member, Method propertySetter) { // If we don't have a backing field and we don't have a setter and getter // don't bother creating a setter delegate if (member.Property.BackingField == null && propertySetter == null) { return; } if (member.Property.BackingField == null && member.Property.Getter != null && member.Property.Setter != null) { // The copies are used to access the property as fake backing fields to avoid // stack overflows by getter and setter calling each other until ethernity member.Property.Getter.Copy(); member.Property.Setter.Copy(); CreateSetterDelegate(builder, propertySetter, member.Property.ReturnType, member.Property); } else if (member.Property.BackingField != null && !member.Property.BackingField.FieldType.IsGenericType) { CreateSetterDelegate(builder, propertySetter, member.Property.BackingField.FieldType, member.Property.BackingField); } else if (member.Property.BackingField == null && member.Property.Setter != null) { var methodSetter = member.Property.Setter.Copy(); propertySetter.NewCoder().Call(methodSetter, CodeBlocks.GetParameter(0)).Return().Replace(); } else if (member.Property.BackingField == null && member.Property.Getter != null) { // This shouldn't be a thing } else { propertySetter.NewCoder().SetValue(member.Property.BackingField, CodeBlocks.GetParameter(0)).Return().Replace(); } }
public static void ImplementPropertyChangedEvent(Builder builder) { var changeAwareInterface = new __IChangeAwareViewModel(); var viewModelInterface = new __IViewModel(); // Get all viewmodels with implemented change aware interface var viewModels = builder.FindTypesByInterface(__IChangeAwareViewModel.Type) .OrderBy(x => { if (x.Implements(__IChangeAwareViewModel.Type, false)) { return(0); } return(1); }); foreach (var vm in viewModels) { if (vm.IsInterface) { continue; } var method = vm.GetMethod("<>RaisePropertyChangedEventRaise", false, typeof(string), typeof(object), typeof(object)); var getIsChangeChangedEvent = __IChangeAwareViewModel.GetIsChangedChanged(vm); var getIsChangeEvent = __IChangeAwareViewModel.GetChanged(vm); if (method == null && getIsChangeChangedEvent != null && getIsChangeEvent != null) { method = vm.CreateMethod(Modifiers.Protected, "<>RaisePropertyChangedEventRaise", typeof(string), typeof(object), typeof(object)); method.NewCoder() .If(x => x.Load(CodeBlocks.GetParameter(0)).Is("IsChanged"), then => then.If(z => z.Load(getIsChangeChangedEvent).IsNotNull(), thenInner => thenInner.Load(getIsChangeChangedEvent).Call(BuilderTypes.EventHandler.GetMethod_Invoke(), CodeBlocks.This, thenInner.NewCoder().NewObj(BuilderTypes.EventArgs.GetMethod_ctor()))) .Call(viewModelInterface.RaisePropertyChanged, CodeBlocks.GetParameter(0)) .Return() ) .If(x => x.Load(getIsChangeEvent).IsNotNull(), then => then.Call(viewModelInterface.RaisePropertyChanged, CodeBlocks.GetParameter(0)) .End .Load(getIsChangeEvent).Call(BuilderTypes.EventHandler1.GetMethod_Invoke().MakeGeneric(changeAwareInterface.PropertyIsChangedEventArgs.ToBuilderType), x => CodeBlocks.This, x => x.NewObj(changeAwareInterface.PropertyIsChangedEventArgs.Ctor, CodeBlocks.GetParameter(0), CodeBlocks.GetParameter(1), CodeBlocks.GetParameter(2))) ) .Return() .Replace(); method.CustomAttributes.AddDebuggerBrowsableAttribute(DebuggerBrowsableState.Never); } if (method == null) { continue; } builder.Log(LogTypes.Info, $"Implementing RaisePropertyChanged Raise Event in '{vm.Fullname}'"); var raisePropertyChanged = vm.GetMethod("RaisePropertyChanged", false, typeof(string), typeof(object), typeof(object)); if (raisePropertyChanged == null) { continue; } if (!raisePropertyChanged.IsAbstract && !raisePropertyChanged.HasMethodBaseCall()) { raisePropertyChanged .NewCoder() .Call(method, CodeBlocks.GetParameter(0), CodeBlocks.GetParameter(1), CodeBlocks.GetParameter(2)) .End .Insert(InsertionPosition.Beginning); } // Repair IsChanged if (!vm.Implements(changeAwareInterface.ToBuilderType, false)) { continue; } var isChangedSetter = vm.GetMethod("set_IsChanged", 1, false); if (isChangedSetter != null) { isChangedSetter.NewCoder() .If(x => x.Call(viewModelInterface.IsLoading).Is(true), then => then.Return()) .Insert(InsertionPosition.Beginning); } } }
internal CecilatorBase(WeaverBase weaver) { this.Initialize(weaver.LogInfo, weaver.LogWarning, weaver.LogWarningPoint, weaver.LogError, weaver.LogErrorPoint); this.moduleDefinition = weaver.ModuleDefinition; this.ReferenceCopyLocal = weaver.ReferenceCopyLocalPaths .Where(x => x.EndsWith(".dll")) .Select(x => LoadAssembly(x)) .Where(x => x != null) .ToArray(); var referencedAssemblies = weaver .With(x => { if (weaver.Config.Attribute("ReferenceRecursive").With(y => y == null ? true : bool.Parse(y.Value))) { return(x.GetAllReferencedAssemblies(weaver.Resolve(this.moduleDefinition.AssemblyReferences))); } return(weaver.Resolve(this.moduleDefinition.AssemblyReferences)); }) .Concat(weaver.References.Split(';').Select(x => LoadAssembly(x))) .Where(x => x != null).ToArray() as IEnumerable <AssemblyDefinition>; if (weaver.Config.Attribute("ReferenceCopyLocal").With(x => x == null ? true : bool.Parse(x.Value))) { referencedAssemblies = referencedAssemblies.Concat(this.ReferenceCopyLocal); } this.ReferencedAssemblies = referencedAssemblies.Distinct(new AssemblyDefinitionEqualityComparer()).ToArray(); this.Log("-----------------------------------------------------------------------------"); foreach (var item in this.ReferencedAssemblies) { this.Log(LogTypes.Info, "<<Assembly>> " + item.Name); } var resourceNames = new List <string>(); foreach (var item in this.moduleDefinition.Resources) { this.Log(LogTypes.Info, "<<Resource>> " + item.Name + " " + item.ResourceType); if (item.ResourceType == ResourceType.Embedded) { var embeddedResource = item as EmbeddedResource; using (var stream = embeddedResource.GetResourceStream()) { var bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); if (bytes[0] == 0xce && bytes[1] == 0xca && bytes[2] == 0xef && bytes[3] == 0xbe) { var resourceCount = BitConverter.ToInt16(bytes.GetBytes(160, 2).Reverse().ToArray(), 0); if (resourceCount > 0) { var startPoint = resourceCount * 8 + 180; for (int i = 0; i < resourceCount; i++) { var length = (int)bytes[startPoint]; var data = Encoding.Unicode.GetString(bytes, startPoint + 1, length).Trim(); startPoint += length + 5; resourceNames.Add(data); this.Log(" " + data); } } } } } } this.ResourceNames = resourceNames.ToArray(); this.allTypes = this.ReferencedAssemblies .SelectMany(x => x.Modules) .Where(x => x != null) .SelectMany(x => x.Types) .Where(x => x != null) .Concat(this.moduleDefinition.Types) .Where(x => x.Module != null && x.Module.Assembly != null) .Select(x => new { Prio = GetAssemblyPrio(x), Type = x }) .OrderBy(x => x.Prio) .ThenBy(x => x.Type.FullName) .Select(x => x.Type) .Distinct(new TypeDefinitionEqualityComparer()) .ToList(); this.Log("-----------------------------------------------------------------------------"); WeaverBase.AllTypes = this.allTypes; this.Identification = CodeBlocks.GenerateName(); }
public Property CreateProperty(Field field, PropertySetterCreationOption setterCreationOption = PropertySetterCreationOption.AlwaysCreate) { var name = $"<{field.Name}>_fieldProperty"; var contain = this.GetProperties().Get(name); if (contain != null) { return(new Property(this, contain)); } var createSetter = setterCreationOption == PropertySetterCreationOption.AlwaysCreate; var attributes = MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Private; if (field.Modifiers.HasFlag(Modifiers.Private)) { attributes |= MethodAttributes.Private; } if (field.Modifiers.HasFlag(Modifiers.Static)) { attributes |= MethodAttributes.Static; } if (field.Modifiers.HasFlag(Modifiers.Public)) { attributes |= MethodAttributes.Public; } if (field.Modifiers.HasFlag(Modifiers.Protected)) { attributes |= MethodAttributes.Family; } if (field.Modifiers.HasFlag(Modifiers.Overrides)) { attributes |= MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.NewSlot; } var property = new PropertyDefinition(name, PropertyAttributes.None, field.FieldType.typeReference) { GetMethod = new MethodDefinition("get_" + name, attributes, field.FieldType.typeReference) }; this.typeDefinition.Properties.Add(property); this.typeDefinition.Methods.Add(property.GetMethod); if (createSetter) { property.SetMethod = new MethodDefinition("set_" + name, attributes, this.moduleDefinition.TypeSystem.Void); property.SetMethod.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, field.FieldType.typeReference)); this.typeDefinition.Methods.Add(property.SetMethod); } var result = new Property(this, property); result.Getter.NewCoder().Load(field).Return().Replace(); if (createSetter) { result.Setter.NewCoder().SetValue(field, CodeBlocks.GetParameter(0)).Return().Replace(); } result.RefreshBackingField(); return(result); }
public Property CreateProperty(Modifiers modifier, BuilderType propertyType, string name, PropertySetterCreationOption setterCreationOption = PropertySetterCreationOption.AlwaysCreate) { var contain = this.GetProperties().Get(name); if (contain != null) { return(new Property(this, contain)); } var createSetter = setterCreationOption == PropertySetterCreationOption.AlwaysCreate; var attributes = MethodAttributes.HideBySig | MethodAttributes.SpecialName; if (modifier.HasFlag(Modifiers.Private)) { attributes |= MethodAttributes.Private; } if (modifier.HasFlag(Modifiers.Static)) { attributes |= MethodAttributes.Static; } if (modifier.HasFlag(Modifiers.Public)) { attributes |= MethodAttributes.Public; } if (modifier.HasFlag(Modifiers.Protected)) { attributes |= MethodAttributes.Family; } var returnType = this.moduleDefinition.ImportReference(propertyType.typeReference); var property = new PropertyDefinition(name, PropertyAttributes.None, returnType); var backingField = this.CreateField(modifier, returnType, $"<{name}>k__BackingField"); // This should be here to insure that the field does not have these attributes... Is that even possible? if (modifier.HasFlag(Modifiers.Overrides)) { attributes |= MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.NewSlot; } property.GetMethod = new MethodDefinition("get_" + name, attributes, returnType); this.typeDefinition.Properties.Add(property); this.typeDefinition.Methods.Add(property.GetMethod); if (createSetter) { property.SetMethod = new MethodDefinition("set_" + name, attributes, this.moduleDefinition.TypeSystem.Void); property.SetMethod.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, returnType)); this.typeDefinition.Methods.Add(property.SetMethod); } var result = new Property(this, property); result.Getter.NewCoder().Load(backingField).Return().Replace(); if (createSetter) { result.Setter.NewCoder().SetValue(backingField, CodeBlocks.GetParameter(0)).Return().Replace(); } result.RefreshBackingField(); return(result); }
private static void CreateSetterDelegate(Builder builder, Method setterDelegateMethod, BuilderType propertyType, object value) { var setterCode = setterDelegateMethod.NewCoder(); T CodeMe <T>(Func <Field, T> fieldCode, Func <Property, T> propertyCode) where T : class { switch (value) { case Field field: return(fieldCode(field)); case Property property: return(propertyCode(property)); default: return(null); } } if (propertyType.ParameterlessContructor != null && propertyType.ParameterlessContructor.IsPublic) { CodeMe( field => setterCode.If(x => x.Load(field).IsNull(), then => then.SetValue(field, x => x.NewObj(propertyType.ParameterlessContructor))), property => setterCode.If(x => x.Call(property.Getter).IsNull(), then => then.Call(property.Setter, x => x.NewObj(propertyType.ParameterlessContructor)))); } // Only this if the property implements idisposable if (propertyType.Implements(typeof(IDisposable))) { CodeMe( field => setterCode.Call(BuilderTypes.Extensions.GetMethod_TryDisposeInternal(), x => x.Load(field)), property => setterCode.Call(BuilderTypes.Extensions.GetMethod_TryDisposeInternal(), x => x.Call(property.Getter))); } setterCode.If(x => x.Load(CodeBlocks.GetParameter(0)).IsNull(), then => { // Just clear if its clearable if (propertyType.Implements(BuilderTypes.IList)) { CodeMe( field => setterCode.Load(field).Call(BuilderTypes.IList.GetMethod_Clear()).Return(), property => setterCode.Call(property.Getter).Call(BuilderTypes.IList.GetMethod_Clear()).Return()); } // Otherwise if the property is not a value type and nullable else if (!propertyType.IsValueType || propertyType.IsNullable || propertyType.IsArray) { CodeMe <CoderBase>( field => setterCode.SetValue(field, null), property => setterCode.Call(property.Setter, null)); } else // otherwise... throw an exception { then.ThrowNew(typeof(NotSupportedException), "Value types does not accept null values."); } return(then); }); setterCode.If(x => CodeMe( field => x.Load(CodeBlocks.GetParameter(0)).Is(field.FieldType), property => x.Load(CodeBlocks.GetParameter(0)).Is(property.ReturnType)), then => CodeMe( field => then.SetValue(field, CodeBlocks.GetParameter(0)).Return(), property => then.Call(property.Setter, CodeBlocks.GetParameter(0)).Return())); if (propertyType.Implements(BuilderTypes.IList)) { var add = propertyType.GetMethod("Add", 1); var array = setterDelegateMethod.GetOrCreateVariable(propertyType.ChildType.MakeArray()); setterCode.SetValue(array, CodeBlocks.GetParameter(0)); setterCode.For(array, (x, item, indexer) => CodeMe( field => x.Load(field).Call(add, item()), property => x.Call(property.Getter).Call(add, item()))); if (!add.ReturnType.IsVoid) { setterCode.Pop(); } } else if (propertyType.Implements(typeof(IEnumerable)) || propertyType.IsArray) { setterCode.If(x => x.Load(CodeBlocks.GetParameter(0)).Is(typeof(IEnumerable)), then => CodeMe( field => then.SetValue(field, CodeBlocks.GetParameter(0)).Return(), property => then.Call(property.Setter, CodeBlocks.GetParameter(0)).Return())) .ThrowNew(typeof(NotSupportedException), "Value does not inherits from IEnumerable"); } else if (propertyType.IsEnum) { // Enums requires special threatment setterCode.If(x => x.Load(CodeBlocks.GetParameter(0)).Is(typeof(string)), then => { var stringVariable = setterDelegateMethod.GetOrCreateVariable(typeof(string)); then.SetValue(stringVariable, CodeBlocks.GetParameter(0)); CodeMe( // Cecilator automagically implements a convertion for this field => then.SetValue(field, stringVariable).Return(), property => then.Call(property.Setter, stringVariable).Return()); return(then); }); CodeMe <CoderBase>( field => setterCode.SetValue(field, CodeBlocks.GetParameter(0)), property => setterCode.Call(property.Setter, CodeBlocks.GetParameter(0))); } else { CodeMe <CoderBase>( field => setterCode.SetValue(field, CodeBlocks.GetParameter(0)), property => setterCode.Call(property.Setter, CodeBlocks.GetParameter(0))); } setterCode.Return().Replace(); }
public void ScripterToScript() { managedScript = ModelsToScriptHelper.TransformModelsToScript(CodeBlocks.ToList()); EditorScript = managedScript.Parse(); }
public void CancelScript() { CodeBlocks.Clear(); Close(); }
private void AddCodeBlocks(CharacterMap map) { var mapParts = new Dictionary <CodeBlock, MapPart>(); var startTagIndex = map.Text.IndexOf("<%", 0); var firstCodeBlockIndex = CodeBlocks.Count; while (startTagIndex != -1) { var endTagIndex = map.Text.IndexOf("%>", startTagIndex + 2); if (endTagIndex == -1) { throw new Exception("No end tag found for code."); } var code = map.Text.Substring(startTagIndex + 2, endTagIndex - startTagIndex - 2); var cb = GetCodeBlock(code); cb.StartText = map[startTagIndex].Element as Text; cb.EndText = map[endTagIndex + 1].Element as Text; CodeBlocks.Add(cb); mapParts.Add(cb, new MapPart { StartIndex = startTagIndex, EndIndex = endTagIndex + 1 }); startTagIndex = map.Text.IndexOf("<%", endTagIndex + 2); } for (var i = CodeBlocks.Count - 1; i >= firstCodeBlockIndex; --i) { // Replace the code of each code block with an empty Text element. var cb = CodeBlocks[i]; cb.Placeholder = map.ReplaceWithText(mapParts[cb], null); //cb.Placeholder = map.ReplaceWithText(mapParts[cb], $"CB{i}"); } for (var i = firstCodeBlockIndex; i < CodeBlocks.Count; ++i) { // Find out where text block ends. var tb = CodeBlocks[i] as TextBlock; if (tb != null) { var bracketLevel = tb.Code.GetCurlyBracketLevelIncrement(); for (var j = i + 1; j < CodeBlocks.Count; ++j) { bracketLevel += CodeBlocks[j].Code.GetCurlyBracketLevelIncrement(); if (bracketLevel <= 0) { tb.EndingCodeBlock = CodeBlocks[j]; break; } } if (tb.EndingCodeBlock == null) { throw new Exception("TextBlock is not terminated with '<% } %>'."); } } } for (var i = CodeBlocks.Count - 1; i >= firstCodeBlockIndex; --i) { CodeBlocks[i].Initialize(); } }
private static void AddPropertySetterInterception( Builder builder, BuilderTypePropertyInterceptionInfo propertyInterceptionInfo, PropertyBuilderInfo member, Field propertyField, Method actionObjectCtor, Method propertySetter, Dictionary <string, Field> interceptorFields) { var syncRoot = BuilderTypes.ISyncRoot; var legalSetterInterceptors = member.InterceptorInfos.Where(x => x.InterfaceSetter != null).ToArray(); member.Property.Setter .NewCoder() .Context(context => { if (member.HasInitializer) { return(context); } for (int i = 0; i < legalSetterInterceptors.Length; i++) { var item = legalSetterInterceptors[i]; var alwaysCreateNewInstance = item.InterceptorInfo.AlwaysCreateNewInstance && item.InterfaceInitializer == null; var fieldOrVariable = interceptorFields[item.Attribute.Identification] as CecilatorBase ?? context.AssociatedMethod.GetOrCreateVariable(item.Attribute.Attribute.Type, item.Attribute.Identification); Coder implementInterceptorInitialization(Coder coder) { coder.SetValue(fieldOrVariable, x => x.NewObj(item.Attribute)); if (item.HasSyncRootInterface) { coder.Load <ICasting>(fieldOrVariable).As(syncRoot.BuilderType.Import()).To <ICallMethod <CallCoder> >().Call(syncRoot.GetMethod_set_SyncRoot(), member.SyncRoot); } ModuleWeaver.ImplementAssignMethodAttribute(builder, legalSetterInterceptors[i].AssignMethodAttributeInfos, fieldOrVariable, item.Attribute.Attribute.Type, coder); return(coder); } if (alwaysCreateNewInstance) { implementInterceptorInitialization(context); } else { context.If(x => x.Load <IRelationalOperators>(fieldOrVariable).IsNull(), then => implementInterceptorInitialization(then)); } item.Attribute.Remove(); } return(context.If(x => x.Load(propertyField).IsNull(), then => then.SetValue(propertyField, x => x.NewObj(propertyInterceptionInfo.GetMethod_ctor(), member.Property.Getter, member.Property.Setter, member.Property.Name, member.Property.ReturnType, CodeBlocks.This, member.Property.ReturnType.IsArray || member.Property.ReturnType.Implements(typeof(IEnumerable)) ? member.Property.ReturnType.ChildType : null, propertySetter == null ? null : x.NewCoder().NewObj(actionObjectCtor, propertySetter.ThisOrNull(), propertySetter))))); }) .Try(@try => { if (member.Property.BackingField == null) { // If we don't have a backing field, we will try getting the value from the // getter itself... But in this case we have to watch out that we don't accidentally code a // StackOverFlow var oldvalue = member.Property.Getter == null ? null : member.Property.Setter.GetOrCreateVariable(member.Property.ReturnType); if (oldvalue != null) { var getter = member.Property.Getter.Copy(); @try.SetValue(oldvalue, y => y.Call(getter)); } for (int i = 0; i < legalSetterInterceptors.Length; i++) { var item = legalSetterInterceptors[i]; var alwaysCreateNewInstance = item.InterceptorInfo.AlwaysCreateNewInstance && item.InterfaceInitializer == null; var fieldOrVariable = interceptorFields[item.Attribute.Identification] as CecilatorBase ?? @try.AssociatedMethod.GetVariable(item.Attribute.Identification); @try.If(x => x.Load <ICasting>(fieldOrVariable) .As(legalSetterInterceptors[i].InterfaceSetter) .To <ICallMethod <BooleanExpressionCallCoder> >() .Call(item.InterfaceSetter.GetMethod_OnSet(), propertyField, oldvalue, CodeBlocks.GetParameter(0)) .To <IRelationalOperators>() .Is(false), then => then.OriginalBody(true)); } } else { @try.If(x => x.And(legalSetterInterceptors, (coder, item, i) => { var fieldOrVariable = interceptorFields[item.Attribute.Identification] as CecilatorBase ?? @try.AssociatedMethod.GetVariable(item.Attribute.Identification); return(coder.Load <ICasting>(fieldOrVariable) .As(legalSetterInterceptors[i].InterfaceSetter) .To <ICallMethod <BooleanExpressionCallCoder> >() .Call(item.InterfaceSetter.GetMethod_OnSet(), propertyField, member.Property.BackingField, CodeBlocks.GetParameter(0))); }).Is(false), then => then.OriginalBody()); } return(@try); }) .Catch(typeof(Exception), (ex, e) => { return(ex.If(x => x.Or(legalSetterInterceptors, (coder, y, i) => { var fieldOrVariable = interceptorFields[y.Attribute.Identification] as CecilatorBase ?? ex.AssociatedMethod.GetVariable(y.Attribute.Identification); return coder.Load <ICasting>(fieldOrVariable) .As(legalSetterInterceptors[i].InterfaceSetter) .To <ICallMethod <BooleanExpressionCallCoder> >() .Call(legalSetterInterceptors[i].InterfaceSetter.GetMethod_OnException(), e()); }).Is(true), then => ex.NewCoder().Rethrow()) .DefaultValue() .Return()); }) .Finally(x => { for (int i = 0; i < legalSetterInterceptors.Length; i++) { var item = legalSetterInterceptors[i]; var fieldOrVariable = interceptorFields[item.Attribute.Identification] as CecilatorBase ?? x.AssociatedMethod.GetVariable(item.Attribute.Identification); x.Load <ICasting>(fieldOrVariable) .As(legalSetterInterceptors[i].InterfaceSetter) .To <ICallMethod <CallCoder> >() .Call(legalSetterInterceptors[i].InterfaceSetter.GetMethod_OnExit()); } return(x); }) .EndTry() .Return() .Replace(); }
public void AddBlock(ITES5CodeBlock block) { CodeBlocks.Add(block); }