internal BindingElementExtensionSectionGenerator(Type bindingElementType, Assembly userAssembly, CodeDomProvider provider) { this.bindingElementType = bindingElementType; this.userAssembly = userAssembly; this.provider = provider; string typePrefix = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement)); this.generatedClassName = typePrefix + Constants.ElementSuffix; this.constantsClassName = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement)) + Constants.ConfigurationStrings; this.defaultValuesClassName = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement)) + Constants.Defaults; this.customBEVarInstance = Helpers.TurnFirstCharLower(bindingElementType.Name); customBEArgRef = new CodeArgumentReferenceExpression(customBEVarInstance); this.customBETypeRef = new CodeTypeReference(bindingElementType.Name); this.customBETypeOfRef = new CodeTypeOfExpression(customBETypeRef); this.customBENewVarAssignRef = new CodeVariableDeclarationStatement( customBETypeRef, customBEVarInstance, new CodeObjectCreateExpression(customBETypeRef)); this.bindingElementMethodParamRef = new CodeParameterDeclarationExpression( CodeDomHelperObjects.bindingElementTypeRef, Constants.bindingElementParamName); }
void EmitArgumentReference(CodeArgumentReferenceExpression Argument) { Depth++; Debug("Emitting argument reference"); Generator.Emit(OpCodes.Ldarg, 0); // for now only used to refer to the sole object[] parameter Depth--; }
public void DefaultConstructor () { CodeArgumentReferenceExpression care = new CodeArgumentReferenceExpression (); Assert.AreEqual (string.Empty, care.ParameterName, "#1"); care.ParameterName = "mono"; Assert.AreEqual ("mono", care.ParameterName, "#2"); }
public void NullParameter () { CodeArgumentReferenceExpression care = new CodeArgumentReferenceExpression ((string) null); Assert.AreEqual (string.Empty, care.ParameterName, "#1"); care.ParameterName = null; Assert.AreEqual (string.Empty, care.ParameterName, "#2"); }
public TypescriptArgumentReferenceExpression( CodeArgumentReferenceExpression codeExpression, CodeGeneratorOptions options) { _codeExpression = codeExpression; _options = options; System.Diagnostics.Debug.WriteLine("TypescriptArgumentReferenceExpression Created"); }
// Generate the CodeDom for our render method internal CodeMemberMethod GenerateRenderMemberMethod(string virtualPath) { Control container = Parent; string physicalPath = HostingEnvironment.MapPath(virtualPath); CodeMemberMethod renderMethod = new CodeMemberMethod(); renderMethod.Name = RenderMethodName; renderMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "__srh")); // REVIEW: we need support for CodeArgumentReferenceExpression, as using a snippet is // not guanranteed to be language agnostic CodeExpression snippetRenderHelper = new CodeArgumentReferenceExpression("__srh"); // Go through all the children to build the CodeDOM tree for (int controlIndex = 0; controlIndex < container.Controls.Count; controlIndex++) { Control c = container.Controls[controlIndex]; if (!(c is SnippetControl || c is ExpressionSnippetControl)) { // If it's a regular control, generate a call to render it based on its index CodeExpression method = new CodeMethodInvokeExpression(snippetRenderHelper, "RenderControl", new CodePrimitiveExpression(controlIndex)); renderMethod.Statements.Add(new CodeExpressionStatement(method)); continue; } BaseCodeControl codeControl = (BaseCodeControl)c; string code = codeControl.Code; CodeStatement stmt; if (codeControl is SnippetControl) { // If it's a <% code %> block, just append the code as is stmt = new CodeSnippetStatement(code); } else { // If it's a <%= expr %> block, generate a call to render it CodeExpression method = new CodeMethodInvokeExpression(snippetRenderHelper, "Render", new CodeSnippetExpression(code)); stmt = new CodeExpressionStatement(method); } stmt.LinePragma = new CodeLinePragma(physicalPath, codeControl.Line); renderMethod.Statements.Add(stmt); } return renderMethod; }
public override void EmitApply (CodeMemberMethod apply, CodeArgumentReferenceExpression proj, CodeArgumentReferenceExpression declloc, CodeArgumentReferenceExpression log, CodeVariableReferenceExpression pb, CodeVariableReferenceExpression tb) { apply.Statements.Add (new CodeCommentStatement ("Create provider for param " + basisparam)); CodeMethodInvokeExpression mie = new CodeMethodInvokeExpression (); mie.Method = new CodeMethodReferenceExpression (proj, "EnsureProvider"); mie.Parameters.Add (new CodeFieldReferenceExpression (CDH.This, basisparam)); mie.Parameters.Add (declloc); apply.Statements.Add (new CodeAssignStatement (pb, mie)); // Tell the PB about our Structure arguments so it can // use them to instantiate the objects we reference. // FIXME: catch if the provider references a rule or template // that requires a structure we don't have. //if (Structure != null) { mie = new CodeMethodInvokeExpression (); mie.Method = new CodeMethodReferenceExpression (pb, "AddContextStructure"); mie.Parameters.Add (CDH.This); apply.Statements.Add (mie); foreach (string param in Structure.Parameters) { if (Structure[param] != StructureParameterKind.Structure) continue; mie = new CodeMethodInvokeExpression (); mie.Method = new CodeMethodReferenceExpression (pb, "AddContextStructure"); mie.Parameters.Add (new CodeFieldReferenceExpression (CDH.This, param)); apply.Statements.Add (mie); } //} foreach (BGTargetBuilder iter in targs) iter.EmitApply (apply, pb, tb, log); foreach (string key in lits.Keys) { CodeExpression val = CDH.ResultExpression (lits[key]); CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression (); cmie.Method = new CodeMethodReferenceExpression (pb, "DefineConstantTarget"); cmie.Parameters.Add (new CodePrimitiveExpression (key)); cmie.Parameters.Add (val); cmie.Parameters.Add (log); apply.Statements.Add (CDH.IfTrueReturnTrue (cmie)); } }
public CodeNamespace GenerateCode(XmlReader reader) { CodeTypeDeclaration templateType = new CodeTypeDeclaration(defaultTypeName); templateType.Attributes = MemberAttributes.Family; templateType.IsPartial = true; CodeNamespace templateNamespace = new CodeNamespace(defaultTargetNamespace); templateNamespace.Types.Add(templateType); AddCommonImports(templateNamespace); CodeMemberMethod renderMethod = new CodeMemberMethod(); renderMethod.Name = "Render"; renderMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; renderMethod.Parameters.Add(new CodeParameterDeclarationExpression( typeof(XmlWriter), "writer")); CodeArgumentReferenceExpression writerExpression = new CodeArgumentReferenceExpression("writer"); templateType.Members.Add(renderMethod); templateType.Members.Add(BuildConverter()); while (reader.Read()) { if (reader.NodeType == XmlNodeType.ProcessingInstruction) { ThrowIfUnknownInstruction(reader); if (typeInstructions.ContainsKey(reader.LocalName)) { ITypeInstruction ti = typeInstructions[reader.LocalName]; ti.Process(reader.Value, templateNamespace, templateType, renderMethod); } if (inlineInstructions.ContainsKey(reader.LocalName)) { IInlineInstruction ii = inlineInstructions[reader.LocalName]; CodeStatementCollection col = ii.Process(reader.Value); renderMethod.Statements.AddRange(col); } } else { renderMethod.Statements.AddRange( generationFunctions[reader.NodeType](reader, writerExpression)); } } return templateNamespace; }
public static void GenerateConstructor(CodeTypeDeclaration classDecl) { CodeConstructor constructorMember = new CodeConstructor() ; constructorMember.Attributes = MemberAttributes.Public; CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(new CodeTypeReference("IContext"), "context"); constructorMember.Parameters.Add(parameter); CodeThisReferenceExpression thisExp = new CodeThisReferenceExpression(); CodeFieldReferenceExpression ctxFieldExp = new CodeFieldReferenceExpression(thisExp, "context"); CodeArgumentReferenceExpression argExp = new CodeArgumentReferenceExpression("context"); CodeAssignStatement assignStatement = new CodeAssignStatement(ctxFieldExp, argExp); constructorMember.Statements.Add(assignStatement); classDecl.Members.Add(constructorMember); }
public void GetKeywordFromCodeDom() { CodeStatement st = new CodeExpressionStatement(new CodeArgumentReferenceExpression("foo")); CodeExpression exp = new CodeArgumentReferenceExpression("foo"); CodeIterationStatement it = new CodeIterationStatement(st, exp, st); CodeConditionStatement cond = new CodeConditionStatement(exp); new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromStatement( it, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions()); new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromStatement( cond, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions()); new Microsoft.VisualBasic.VBCodeProvider().GenerateCodeFromStatement( it, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions()); new Microsoft.VisualBasic.VBCodeProvider().GenerateCodeFromStatement( cond, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions()); }
public CodeStatement GenerateExecuteQueryBody(CodeMemberMethod method) { var dataAccessReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), DataAccessVariableName); var methodArgumentReferences = new CodeArgumentReferenceExpression[method.Parameters.Count]; for (int i = 0; i < method.Parameters.Count; i++) { methodArgumentReferences[i] = new CodeArgumentReferenceExpression(method.Parameters[i].Name); } var invocationExpression = new CodeMethodInvokeExpression(dataAccessReference, ExecuteSqlQueryMethodName, methodArgumentReferences); if (method.ReturnType.BaseType != "System.Void") { return new CodeMethodReturnStatement(invocationExpression); } else { return new CodeExpressionStatement(invocationExpression); } }
static CodeMemberMethod addDispose(CodeTypeDeclaration ctd, CodeMemberMethod m, CodeMemberField fContainer) { CodeArgumentReferenceExpression ar0; CodeConditionStatement ccs, ccs1; CodeFieldReferenceExpression fr; ar0 = new CodeArgumentReferenceExpression("disposing"); ctd.Members.Add(m = new CodeMemberMethod()); m.Name = "Dispose"; m.Attributes = MemberAttributes.Override | MemberAttributes.Family; m.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), ar0.ParameterName)); fr = new CodeFieldReferenceExpression(null, fContainer.Name); ccs = new CodeConditionStatement(ar0, ccs1 = new CodeConditionStatement()); ccs1.Condition = new CodeBinaryOperatorExpression( fr, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression()); ccs1.TrueStatements.Add( new CodeExpressionStatement( new CodeMethodInvokeExpression(fr, "Dispose"))); m.Statements.AddRange( new CodeStatement[] { ccs, new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeBaseReferenceExpression(), "Dispose",ar0)) }); m.Comments.AddRange( new CodeCommentStatement[]{ new CodeCommentStatement("<summary>\n Clean up any resources being used.\n </summary>",true) } ); return m; }
internal void ConnectNameAndEvents(string elementName, ArrayList events, int connectionId) { CodeContext cc = (CodeContext)_codeContexts.Peek(); bool isAllowedNameScope = cc.IsAllowedNameScope; if (_codeContexts.Count > 1 && KnownTypes.Types[(int)KnownElements.INameScope].IsAssignableFrom(cc.ElementType)) { cc.IsAllowedNameScope = false; } if ((elementName == null || !isAllowedNameScope) && (events == null || events.Count == 0)) { _typeArgsList = null; return; } EnsureHookupFn(); CodeConditionStatement ccsConnector = null; if (SwitchStatementSupported()) { // case 1: // CodeSnippetStatement cssCase = new CodeSnippetStatement(CASE_STATEMENT + connectionId + COLON); _ccRoot.HookupFn.Statements.Add(cssCase); } else { // if (connectionId == 1) // ccsConnector = new CodeConditionStatement(); ccsConnector.Condition = new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CONNECTIONID), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(connectionId)); } // (System.Windows.Controls.Footype)target; CodeArgumentReferenceExpression careTarget = new CodeArgumentReferenceExpression(TARGET); CodeCastExpression cceTarget = new CodeCastExpression(cc.ElementTypeReference, careTarget); CodeExpression ceEvent = cceTarget; // Names in nested Name scopes not be hooked up via ICC.Connect() as no fields are generated in this case. if (elementName != null && isAllowedNameScope) { // this.fooId = (System.Windows.Controls.Footype)target; // ceEvent = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), elementName); CodeAssignStatement casName = new CodeAssignStatement(ceEvent, cceTarget); if (SwitchStatementSupported()) { _ccRoot.HookupFn.Statements.Add(casName); } else { ccsConnector.TrueStatements.Add(casName); } } if (events != null) { foreach (MarkupEventInfo mei in events) { CodeStatement csEvent = AddCLREvent(cc, ceEvent, mei); if (SwitchStatementSupported()) { _ccRoot.HookupFn.Statements.Add(csEvent); } else { ccsConnector.TrueStatements.Add(csEvent); } } } // return; // if (SwitchStatementSupported()) { _ccRoot.HookupFn.Statements.Add(new CodeMethodReturnStatement()); } else { ccsConnector.TrueStatements.Add(new CodeMethodReturnStatement()); _ccRoot.HookupFn.Statements.Add(ccsConnector); } _typeArgsList = null; }
private void GenerateInternalTypeHelperImplementation() { if (!IsInternalAccessSupported || !(HasInternals || HasLocalReference) || _hasGeneratedInternalTypeHelper) { return; } _hasGeneratedInternalTypeHelper = true; // namespace XamlGeneratedNamespace // { // CodeNamespace cns = new CodeNamespace(); cns.Name = XamlTypeMapper.GeneratedNamespace; // [EditorBrowsable(EditorBrowsableState.Never)] // public sealed class GeneratedInternalTypeHelper : InternalTypeHelper // { // CodeTypeDeclaration ctdClass = new CodeTypeDeclaration(); ctdClass.Name = XamlTypeMapper.GeneratedInternalTypeHelperClassName; ctdClass.BaseTypes.Add(new CodeTypeReference("System.Windows.Markup.InternalTypeHelper")); ctdClass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed; AddDebuggerNonUserCodeAttribute(ctdClass); AddGeneratedCodeAttribute(ctdClass); AddEditorBrowsableAttribute(ctdClass); GenerateXmlComments(ctdClass, ctdClass.Name); // protected override object CreateInstance(Type type, CultureInfo culture) // { // return Activator.CreateInstance(type, // BindingFlags.Public | // BindingFlags.NonPublic | // BindingFlags.Instance | // BindingFlags.CreateInstance, // null, // null, // culture); // } // CodeMemberMethod cmmCI = new CodeMemberMethod(); cmmCI.Name = "CreateInstance"; cmmCI.Attributes = MemberAttributes.Family | MemberAttributes.Override; cmmCI.ReturnType = new CodeTypeReference(typeof(Object)); CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(Type), TYPE); CodeParameterDeclarationExpression param4 = new CodeParameterDeclarationExpression(typeof(CultureInfo), CULTURE); cmmCI.Parameters.Add(param1); cmmCI.Parameters.Add(param4); CodeMethodReferenceExpression cmreCI = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Activator)), "CreateInstance"); CodeMethodInvokeExpression cmieCI = new CodeMethodInvokeExpression(); cmieCI.Method = cmreCI; cmieCI.Parameters.Add(new CodeArgumentReferenceExpression(TYPE)); CodeFieldReferenceExpression cfre1 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Public"); CodeFieldReferenceExpression cfre2 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "NonPublic"); CodeFieldReferenceExpression cfre3 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Instance"); CodeFieldReferenceExpression cfre4 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "CreateInstance"); CodeBinaryOperatorExpression cboe1 = new CodeBinaryOperatorExpression(cfre1, CodeBinaryOperatorType.BitwiseOr, cfre2); CodeBinaryOperatorExpression cboe2 = new CodeBinaryOperatorExpression(cfre3, CodeBinaryOperatorType.BitwiseOr, cfre4); CodeBinaryOperatorExpression cboeCI = new CodeBinaryOperatorExpression(cboe1, CodeBinaryOperatorType.BitwiseOr, cboe2); cmieCI.Parameters.Add(cboeCI); cmieCI.Parameters.Add(new CodePrimitiveExpression(null)); cmieCI.Parameters.Add(new CodePrimitiveExpression(null)); cmieCI.Parameters.Add(new CodeArgumentReferenceExpression(CULTURE)); cmmCI.Statements.Add(new CodeMethodReturnStatement(cmieCI)); GenerateXmlComments(cmmCI, cmmCI.Name); ctdClass.Members.Add(cmmCI); // protected override object GetPropertyValue(PropertyInfo propertyInfo, object target, CultureInfo culture) // { // return propertyInfo.GetValue(target, BindingFlags.Default, null, null, culture); // } // CodeMemberMethod cmmGPV = new CodeMemberMethod(); cmmGPV.Name = "GetPropertyValue"; cmmGPV.Attributes = MemberAttributes.Family | MemberAttributes.Override; cmmGPV.ReturnType = new CodeTypeReference(typeof(Object)); param1 = new CodeParameterDeclarationExpression(typeof(PropertyInfo), PROPINFO); CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression(typeof(object), TARGET); cmmGPV.Parameters.Add(param1); cmmGPV.Parameters.Add(param2); cmmGPV.Parameters.Add(param4); CodeMethodReferenceExpression cmreGPV = new CodeMethodReferenceExpression(new CodeArgumentReferenceExpression(PROPINFO), "GetValue"); CodeMethodInvokeExpression cmieGPV = new CodeMethodInvokeExpression(); cmieGPV.Method = cmreGPV; cmieGPV.Parameters.Add(new CodeArgumentReferenceExpression(TARGET)); cmieGPV.Parameters.Add(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), DEFAULT)); cmieGPV.Parameters.Add(new CodePrimitiveExpression(null)); cmieGPV.Parameters.Add(new CodePrimitiveExpression(null)); cmieGPV.Parameters.Add(new CodeArgumentReferenceExpression(CULTURE)); cmmGPV.Statements.Add(new CodeMethodReturnStatement(cmieGPV)); GenerateXmlComments(cmmGPV, cmmGPV.Name); ctdClass.Members.Add(cmmGPV); // protected override void SetPropertyValue(PropertyInfo propertyInfo, object target, object value, CultureInfo culture) // { // propertyInfo.SetValue(target, value, BindingFlags.Default, null, null, culture); // } // CodeMemberMethod cmmSPV = new CodeMemberMethod(); cmmSPV.Name = "SetPropertyValue"; cmmSPV.Attributes = MemberAttributes.Family | MemberAttributes.Override; CodeParameterDeclarationExpression param3 = new CodeParameterDeclarationExpression(typeof(object), VALUE); cmmSPV.Parameters.Add(param1); cmmSPV.Parameters.Add(param2); cmmSPV.Parameters.Add(param3); cmmSPV.Parameters.Add(param4); CodeMethodReferenceExpression cmreSPV = new CodeMethodReferenceExpression(new CodeArgumentReferenceExpression(PROPINFO), "SetValue"); CodeMethodInvokeExpression cmieSPV = new CodeMethodInvokeExpression(); cmieSPV.Method = cmreSPV; cmieSPV.Parameters.Add(new CodeArgumentReferenceExpression(TARGET)); cmieSPV.Parameters.Add(new CodeArgumentReferenceExpression(VALUE)); cmieSPV.Parameters.Add(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), DEFAULT)); cmieSPV.Parameters.Add(new CodePrimitiveExpression(null)); cmieSPV.Parameters.Add(new CodePrimitiveExpression(null)); cmieSPV.Parameters.Add(new CodeArgumentReferenceExpression(CULTURE)); cmmSPV.Statements.Add(new CodeExpressionStatement(cmieSPV)); GenerateXmlComments(cmmSPV, cmmSPV.Name); ctdClass.Members.Add(cmmSPV); // protected override Delegate CreateDelegate(Type delegateType, object target, string handler) // { // return (Delegate)target.GetType().InvokeMember("_CreateDelegate", // BindingFlags.Instance | // BindingFlags.NonPublic | // BindingFlags.InvokeMethod, // null, // target, // new object[] { delegateType, handler }); // } // CodeMemberMethod cmmCD = new CodeMemberMethod(); cmmCD.Name = "CreateDelegate"; cmmCD.Attributes = MemberAttributes.Family | MemberAttributes.Override; cmmCD.ReturnType = new CodeTypeReference(typeof(Delegate)); param1 = new CodeParameterDeclarationExpression(typeof(Type), DELEGATETYPE); param3 = new CodeParameterDeclarationExpression(typeof(string), HANDLERARG); cmmCD.Parameters.Add(param1); cmmCD.Parameters.Add(param2); cmmCD.Parameters.Add(param3); CodeArgumentReferenceExpression careTarget = new CodeArgumentReferenceExpression(TARGET); CodeMethodReferenceExpression cmreGetType = new CodeMethodReferenceExpression(careTarget, "GetType"); CodeMethodInvokeExpression cmieGetType = new CodeMethodInvokeExpression(); cmieGetType.Method = cmreGetType; CodeMethodReferenceExpression cmreCD = new CodeMethodReferenceExpression(cmieGetType, "InvokeMember"); CodeMethodInvokeExpression cmieCD = new CodeMethodInvokeExpression(); cmieCD.Method = cmreCD; cmieCD.Parameters.Add(new CodePrimitiveExpression(CREATEDELEGATEHELPER)); CodeFieldReferenceExpression cfre5 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "InvokeMethod"); CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression(cfre2, CodeBinaryOperatorType.BitwiseOr, cfre3); CodeBinaryOperatorExpression cboeCD = new CodeBinaryOperatorExpression(cfre5, CodeBinaryOperatorType.BitwiseOr, cboe); cmieCD.Parameters.Add(cboeCD); cmieCD.Parameters.Add(new CodePrimitiveExpression(null)); cmieCD.Parameters.Add(careTarget); CodeArrayCreateExpression caceCD = new CodeArrayCreateExpression(typeof(object)); CodeArgumentReferenceExpression careDelType = new CodeArgumentReferenceExpression(DELEGATETYPE); CodeArgumentReferenceExpression careHandler = new CodeArgumentReferenceExpression(HANDLERARG); caceCD.Initializers.Add(careDelType); caceCD.Initializers.Add(careHandler); cmieCD.Parameters.Add(caceCD); cmieCD.Parameters.Add(new CodePrimitiveExpression(null)); CodeCastExpression cceCD = new CodeCastExpression(typeof(Delegate), cmieCD); cmmCD.Statements.Add(new CodeMethodReturnStatement(cceCD)); GenerateXmlComments(cmmCD, cmmCD.Name); ctdClass.Members.Add(cmmCD); // protected override void AddEventHandler(EventInfo eventInfo, object target, Delegate handler); // { // eventInfo.AddEventHandler(target, handler); // } // CodeMemberMethod cmmAEH = new CodeMemberMethod(); cmmAEH.Name = "AddEventHandler"; cmmAEH.Attributes = MemberAttributes.Family | MemberAttributes.Override; param1 = new CodeParameterDeclarationExpression(typeof(EventInfo), EVENTINFO); param3 = new CodeParameterDeclarationExpression(typeof(Delegate), HANDLERARG); cmmAEH.Parameters.Add(param1); cmmAEH.Parameters.Add(param2); cmmAEH.Parameters.Add(param3); CodeMethodReferenceExpression cmreAEH = new CodeMethodReferenceExpression(new CodeArgumentReferenceExpression(EVENTINFO), "AddEventHandler"); CodeMethodInvokeExpression cmieAEH = new CodeMethodInvokeExpression(); cmieAEH.Method = cmreAEH; cmieAEH.Parameters.Add(new CodeArgumentReferenceExpression(TARGET)); cmieAEH.Parameters.Add(new CodeArgumentReferenceExpression(HANDLERARG)); cmmAEH.Statements.Add(new CodeExpressionStatement(cmieAEH)); GenerateXmlComments(cmmAEH, cmmAEH.Name); ctdClass.Members.Add(cmmAEH); // } // cns.Types.Add(ctdClass); // } // CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cns); // For VB only we need to let the parser know about the RootNamespace value // in order to look for the XamlGeneratedNamespace.GeneratedInternalTypeHelper // type whose full type name would have been implicitly by the VB comopiler to // RootNS.XamlGeneratedNamespace.GeneratedInternalTypeHelper if (IsLanguageVB && !string.IsNullOrEmpty(DefaultNamespace)) { // [assembly: RootNamespaceAttribute("RootNS")] CodeAttributeDeclaration cad = new CodeAttributeDeclaration( "System.Windows.Markup.RootNamespaceAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(DefaultNamespace))); ccu.AssemblyCustomAttributes.Add(cad); } MemoryStream codeMemStream = new MemoryStream(); // using Disposes the StreamWriter when it ends. Disposing the StreamWriter // also closes the underlying MemoryStream. Furthermore, don't add BOM here since // TaskFileService.WriteGeneratedCodeFile adds it. using (StreamWriter codeStreamWriter = new StreamWriter(codeMemStream, new UTF8Encoding(false))) { CodeGeneratorOptions o = new CodeGeneratorOptions(); CodeDomProvider codeProvider = EnsureCodeProvider(); codeProvider.GenerateCodeFromCompileUnit(ccu, codeStreamWriter, o); codeStreamWriter.Flush(); TaskFileService.WriteGeneratedCodeFile(codeMemStream.ToArray(), TargetPath + SharedStrings.GeneratedInternalTypeHelperFileName, SharedStrings.GeneratedExtension, SharedStrings.IntellisenseGeneratedExtension, LanguageSourceExtension); } }
private CodeExpression[] ExportMessages (MessageDescriptionCollection messages, CodeMemberMethod method, bool return_args) { CodeExpression [] args = null; foreach (MessageDescription md in messages) { if (md.Direction == MessageDirection.Output) { if (md.Body.ReturnValue != null) { ExportDataContract (md.Body.ReturnValue); method.ReturnType = md.Body.ReturnValue.CodeTypeReference; } continue; } if (return_args) args = new CodeExpression [md.Body.Parts.Count]; MessagePartDescriptionCollection parts = md.Body.Parts; for (int i = 0; i < parts.Count; i++) { ExportDataContract (parts [i]); method.Parameters.Add ( new CodeParameterDeclarationExpression ( parts [i].CodeTypeReference, parts [i].Name)); if (return_args) args [i] = new CodeArgumentReferenceExpression (parts [i].Name); } } return args; }
protected override void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e) { this.OutputIdentifier(e.ParameterName); }
protected override void GenerateArgumentReferenceExpression (CodeArgumentReferenceExpression e) { }
protected override void AddStatementsToInitMethod (CodeMemberMethod method) { #if NET_2_0 AddStatementsFromDirective (method); ILocation directiveLocation = pageParser.DirectiveLocation; CodeArgumentReferenceExpression ctrlVar = new CodeArgumentReferenceExpression("__ctrl"); if (pageParser.Title != null) method.Statements.Add (AddLinePragma (CreatePropertyAssign (ctrlVar, "Title", pageParser.Title), directiveLocation)); if (pageParser.MasterPageFile != null) method.Statements.Add (AddLinePragma (CreatePropertyAssign (ctrlVar, "MasterPageFile", pageParser.MasterPageFile), directiveLocation)); if (pageParser.Theme != null) method.Statements.Add (AddLinePragma (CreatePropertyAssign (ctrlVar, "Theme", pageParser.Theme), directiveLocation)); if (pageParser.StyleSheetTheme != null) method.Statements.Add (AddLinePragma (CreatePropertyAssign (ctrlVar, "StyleSheetTheme", pageParser.StyleSheetTheme), directiveLocation)); if (pageParser.Async != false) method.Statements.Add (AddLinePragma (CreatePropertyAssign (ctrlVar, "AsyncMode", pageParser.Async), directiveLocation)); if (pageParser.AsyncTimeout != -1) method.Statements.Add (AddLinePragma (CreatePropertyAssign (ctrlVar, "AsyncTimeout", TimeSpan.FromSeconds (pageParser.AsyncTimeout)), directiveLocation)); CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (thisRef, "InitializeCulture"); method.Statements.Add (AddLinePragma (new CodeExpressionStatement (expr), directiveLocation)); #endif }
private void CreateVertexInputMethods() { AsmListing asmVS = this.source.GetAsmTechnique(this.techniqueName, this.platform).VertexShader; //create the GetVertexInputCount() and GetVertexInput() methods CodeMemberMethod count = new CodeMemberMethod(); count.Name = "GetVertexInputCountImpl"; count.Attributes = MemberAttributes.Family | MemberAttributes.Override; count.ReturnType = new CodeTypeReference(typeof(int)); Comment(count, "Returns the number of vertex inputs used by this shader"); count.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(asmVS.InputCount))); classDom.Members.Add(count); //inputs are stored in a static array //create it... int[] arrayValues = new int[asmVS.InputCount * 2]; for (int i = 0; i < asmVS.InputCount; i++) { arrayValues[i] = (int)asmVS.GetInput(i).Usage; arrayValues[i + asmVS.InputCount] = (int)asmVS.GetInput(i).Index; } this.vsInputField = new CodeMemberField(typeof(int[]), "vin"); this.vsInputField.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; this.vsInputField.InitExpression = ShaderBytes.ToArray(arrayValues, this.directives); CodeFieldReferenceExpression vsInputRef = new CodeFieldReferenceExpression(ShaderClassEx, vsInputField.Name); //protected internal abstract void GetVertexInput(int index, out VertexElementUsage elementUsage, out int elementIndex); CodeMemberMethod getInput = new CodeMemberMethod(); getInput.Name = "GetVertexInputImpl"; getInput.Attributes = MemberAttributes.Family | MemberAttributes.Override; CodeParameterDeclarationExpression indexParam = new CodeParameterDeclarationExpression(typeof(int),"i"); getInput.Parameters.Add(indexParam); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(VertexElementUsage), "usage"); param.Direction = FieldDirection.Out; getInput.Parameters.Add(param); param = new CodeParameterDeclarationExpression(typeof(int), "index"); param.Direction = FieldDirection.Out; getInput.Parameters.Add(param); CodeArgumentReferenceExpression indexRef = new CodeArgumentReferenceExpression(indexParam.Name); //the element index is stored at 'i + asmVS.InputCount' CodeExpression indexArray = new CodeArrayIndexerExpression(vsInputRef, new CodeBinaryOperatorExpression(indexRef, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(asmVS.InputCount))); //and the usage must be cast CodeExpression usageCast = new CodeCastExpression(typeof(VertexElementUsage), new CodeArrayIndexerExpression(vsInputRef,indexRef)); getInput.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("usage"), usageCast)); getInput.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("index"), indexArray)); Comment(getInput, "Returns a vertex input used by this shader"); classDom.Members.Add(getInput); }
//implement the code generation methods private void SetupMembers(string name) { shaderTypeRef = new CodeTypeReference(name); gdIndexRef = new CodeFieldReferenceExpression(ShaderClassEx, "gd"); shaderSystemDecl = new CodeParameterDeclarationExpression(typeof(ShaderSystemBase), "state"); shaderSystemRef = new CodeArgumentReferenceExpression("state"); graphicsIDInit = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "gdInit"); validateDeviceId = new CodeConditionStatement(new CodeBinaryOperatorExpression(GraphicsDeviceUID, CodeBinaryOperatorType.IdentityInequality, new CodePropertyReferenceExpression(ShaderSystemRef, "DeviceUniqueIndex")), new CodeExpressionStatement(new CodeMethodInvokeExpression(graphicsIDInit, shaderSystemRef))); validateDeviceIdAndWarmShader = new CodeConditionStatement(new CodeBinaryOperatorExpression(GraphicsDeviceUID, CodeBinaryOperatorType.IdentityInequality, new CodePropertyReferenceExpression(ShaderSystemRef, "DeviceUniqueIndex")), new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "WarmShader", shaderSystemRef))); bindInstanceChange = new CodeVariableReferenceExpression("ic"); //bindTypeChange = new CodeVariableReferenceExpression("tc"); extensionModeChange = new CodeVariableReferenceExpression("ec"); shaderExtensionMode = new CodeVariableReferenceExpression("ext"); shaderExtensionIsBlending = new CodeBinaryOperatorExpression(shaderExtensionMode, CodeBinaryOperatorType.IdentityEquality, new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(ShaderExtension)), "Blending")); shaderExtensionIsInstancing = new CodeBinaryOperatorExpression(shaderExtensionMode, CodeBinaryOperatorType.IdentityEquality, new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(ShaderExtension)), "Instancing")); effectRef = new CodeFieldReferenceExpression(ShaderClassEx, "fx"); effectBytesRef = new CodeFieldReferenceExpression(ShaderClassEx, "fxb"); vsRegRef = new CodeFieldReferenceExpression(Instance, "vreg"); psRegRef = new CodeFieldReferenceExpression(Instance, "preg"); vsRegChangeRef = new CodeFieldReferenceExpression(Instance, "vreg_change"); psRegChangeRef = new CodeFieldReferenceExpression(Instance, "preg_change"); vsBlendRegRef = new CodeFieldReferenceExpression(Instance, "vbreg"); vsInstancingRegRef = new CodeFieldReferenceExpression(Instance, "vireg"); vsBlendRegChangeRef = new CodeFieldReferenceExpression(Instance, "vbreg_change"); vsInstancingRegChangeRef = new CodeFieldReferenceExpression(Instance, "vireg_change"); vsBooleanRegRef = new CodeFieldReferenceExpression(Instance, "vreg_bool"); psBooleanRegRef = new CodeFieldReferenceExpression(Instance, "preg_bool"); vsBooleanRegChangeRef = new CodeFieldReferenceExpression(Instance, "vreg_bool_change"); psBooleanRegChangeRef = new CodeFieldReferenceExpression(Instance, "preg_bool_change"); setAttribIdRef = new CodeArgumentReferenceExpression("id"); setAttribValueRef = new CodeArgumentReferenceExpression("value"); }
protected override void GenerateArgumentReferenceExpression (CodeArgumentReferenceExpression expression) { Output.Write (CreateEscapedIdentifier (expression.ParameterName)); }
protected override void GenerateArgumentReferenceExpression(System.CodeDom.CodeArgumentReferenceExpression e) { throw new Exception("The method or operation is not implemented."); }
private static void AddConstructorWithCopiedParameters(CodeTypeDeclaration codeType, Type implementationType, CodeFieldReferenceExpression omObjectFieldReference, ConstructorInfo constructorInfo) { CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; ParameterInfo[] parameters = constructorInfo.GetParameters(); CodeExpression[] codeArgumentReferences = new CodeExpression[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { bool isOmTypeArg = false; string paramType = parameters[i].ParameterType.FullName; if (OMtoPSClassMappings.ContainsKey(paramType)) { paramType = OMtoPSClassMappings[paramType]; isOmTypeArg = true; } string paramName = parameters[i].Name; string passedInArg; // Create the proper parameter for optional if (parameters[i].IsOptional) { paramName = paramType.Contains("System") ? string.Format("{0} = null", parameters[i].Name) : string.Format("{0} = default({1})", parameters[i].Name, paramType); } // Need to do a null check for calling an omObject from a PS wrapper class if (isOmTypeArg && parameters[i].IsOptional) { CodeVariableDeclarationStatement omObjectDeclaration = new CodeVariableDeclarationStatement( parameters[i].ParameterType, string.Format("{0}{1}", parameters[i].Name, "OmObject"), new CodePrimitiveExpression(null)); constructor.Statements.Add(omObjectDeclaration); CodeArgumentReferenceExpression omObjectArgumentReference = new CodeArgumentReferenceExpression(parameters[i].Name); CodeAssignStatement omObjectAssignStatement = new CodeAssignStatement(new CodeVariableReferenceExpression(string.Format("{0}{1}", parameters[i].Name, "OmObject")), new CodeVariableReferenceExpression(string.Format("{0}.{1}", parameters[i].Name, OmObject))); CodeBinaryOperatorExpression nullCheck = new CodeBinaryOperatorExpression(omObjectArgumentReference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)); // if the parameter is not null, use the omObject of the PS Wrapper class constructor.Statements.Add(new CodeConditionStatement(nullCheck, omObjectAssignStatement)); passedInArg = string.Format("{0}{1}", parameters[i].Name, "OmObject"); } else if (isOmTypeArg) { passedInArg = string.Format("{0}.{1}", parameters[i].Name, OmObject); } else { passedInArg = parameters[i].Name; } codeArgumentReferences[i] = new CodeArgumentReferenceExpression(passedInArg); constructor.Parameters.Add(new CodeParameterDeclarationExpression(paramType, paramName)); } CodeObjectCreateExpression createExpression = new CodeObjectCreateExpression(implementationType, codeArgumentReferences); constructor.Statements.Add(new CodeAssignStatement(omObjectFieldReference, createExpression)); codeType.Members.Add(constructor); }
private static CodeMemberMethod AddSetPropertiesMethod(this IMessage message, SetPropertiesType setType = SetPropertiesType.Constructor) { var type = new CodeTypeReference(message.Name.PascalCased()); var method = new CodeMemberMethod { Name = "WithProperties", ReturnType = type, Attributes = MemberAttributes.Public }; var parameters = new List<CodeExpression>(); var properties = new List<MessageProperty>(message.Interfaces.SelectMany(i => i.Properties)) .Union(message.Properties).Distinct(MessageProperty.NameComparer); var messageProperties = properties as MessageProperty[] ?? properties.ToArray(); foreach (var property in messageProperties.OrderBy(x => x.Optional)) { var camelCased = property.Name.CamelCased(); var pascalCased = property.Name.PascalCased(); if (pascalCased == Globals.EventGenerationDateProperty) continue; var typeName = property.Type.SafeTypeName(); method.Parameters.Add(new CodeParameterDeclarationExpression(typeName, $"{camelCased} = default({typeName})")); var variableName = $"local{pascalCased}"; var argumentReference = new CodeArgumentReferenceExpression(camelCased); var variable = new CodeVariableDeclarationStatement(typeName, variableName, argumentReference); method.Statements.Add(variable); var ifDefaultValue = new CodeBinaryOperatorExpression(argumentReference, CodeBinaryOperatorType.ValueEquality, new CodeDefaultValueExpression(new CodeTypeReference(typeName))); var variableReference = new CodeVariableReferenceExpression(variableName); parameters.Add(variableReference); var condition = new CodeConditionStatement(ifDefaultValue, new CodeAssignStatement(variableReference, new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), pascalCased))); method.Statements.Add(condition); } if (setType == SetPropertiesType.Constructor) { var create = new CodeObjectCreateExpression(type, parameters.ToArray()); method.Statements.Add(new CodeMethodReturnStatement(create)); } else { var name = $"_{Guid.NewGuid():n}"; var instance = new CodeVariableDeclarationStatement(type, name, new CodeObjectCreateExpression(type)); var instanceReference = new CodeVariableReferenceExpression(name); method.Statements.Add(instance); foreach (var property in messageProperties.OrderBy(x => x.Optional)) { var propertyReference = new CodePropertyReferenceExpression(instanceReference, property.Name.PascalCased()); method.Statements.Add(new CodeAssignStatement(propertyReference, new CodeArgumentReferenceExpression($"local{property.Name.PascalCased()}"))); } method.Statements.Add(new CodeMethodReturnStatement(instanceReference)); } return method; }
internal void ConnectStyleEvent(XamlClrEventNode xamlClrEventNode) { CodeConditionStatement ccsConnector = null; // validate the event handler name per C# grammar for identifiers ValidateEventHandlerName(xamlClrEventNode.EventName, xamlClrEventNode.Value); EnsureStyleConnector(); if (!xamlClrEventNode.IsSameScope) { int connectionId = xamlClrEventNode.ConnectionId; if (SwitchStatementSupported()) { // break any previous case staements as we are starting a new connection scope. if (_ccRoot.StyleConnectorFn.Statements.Count > 1) { CodeSnippetStatement cssBreak = new CodeSnippetStatement(BREAK_STATEMENT); _ccRoot.StyleConnectorFn.Statements.Add(cssBreak); } // case 1: // CodeSnippetStatement cssCase = new CodeSnippetStatement(CASE_STATEMENT + connectionId + COLON); _ccRoot.StyleConnectorFn.Statements.Add(cssCase); } else { // if (connectionId == 1) // ccsConnector = new CodeConditionStatement(); ccsConnector.Condition = new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CONNECTIONID), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(connectionId)); } } else if (!SwitchStatementSupported()) { // if in the same scope then use the if statement that was last generated // at the start of the scope Debug.Assert(_ccRoot.StyleConnectorFn.Statements.Count > 0); ccsConnector = _ccRoot.StyleConnectorFn.Statements[_ccRoot.StyleConnectorFn.Statements.Count - 1] as CodeConditionStatement; Debug.Assert(ccsConnector != null); } CodeArgumentReferenceExpression careTarget = new CodeArgumentReferenceExpression(TARGET); if (xamlClrEventNode.IsStyleSetterEvent) { // EventSetter declaration only once to avoid warning! if (!_hasEmittedEventSetterDeclaration) { _hasEmittedEventSetterDeclaration = true; // EventSetter eventSetter; // CodeVariableDeclarationStatement cvdsES = new CodeVariableDeclarationStatement(KnownTypes.Types[(int)KnownElements.EventSetter], EVENTSETTER); _ccRoot.StyleConnectorFn.Statements.Insert(0, cvdsES); } // eventSetter = new EventSetter(); // CodeExpression[] esParams = {}; CodeVariableReferenceExpression cvreES = new CodeVariableReferenceExpression(EVENTSETTER); CodeAssignStatement casES = new CodeAssignStatement(cvreES, new CodeObjectCreateExpression(KnownTypes.Types[(int)KnownElements.EventSetter], esParams)); // eventSetter.Event = Button.ClickEvent; // CodePropertyReferenceExpression cpreEvent = new CodePropertyReferenceExpression(cvreES, EVENT); CodeAssignStatement casEvent = new CodeAssignStatement(cpreEvent, GetEvent(xamlClrEventNode.EventMember, xamlClrEventNode.EventName, xamlClrEventNode.Value)); // eventSetter.Handler = new RoutedEventHandler(OnClick); // CodePropertyReferenceExpression cpreHandler = new CodePropertyReferenceExpression(cvreES, HANDLER); CodeAssignStatement casHandler = new CodeAssignStatement(cpreHandler, GetEventDelegate(null, xamlClrEventNode.EventMember, xamlClrEventNode.EventName, xamlClrEventNode.Value)); AddLinePragma(casHandler, xamlClrEventNode.LineNumber); // ((Style)target).Setters.Add(eventSetter); // CodeCastExpression cceTarget = new CodeCastExpression(KnownTypes.Types[(int)KnownElements.Style], careTarget); CodePropertyReferenceExpression cpreSetters = new CodePropertyReferenceExpression(cceTarget, SETTERS); CodeMethodInvokeExpression cmieAdd = new CodeMethodInvokeExpression(cpreSetters, ADD, cvreES); if (SwitchStatementSupported()) { _ccRoot.StyleConnectorFn.Statements.Add(casES); _ccRoot.StyleConnectorFn.Statements.Add(casEvent); _ccRoot.StyleConnectorFn.Statements.Add(casHandler); _ccRoot.StyleConnectorFn.Statements.Add(new CodeExpressionStatement(cmieAdd)); } else { ccsConnector.TrueStatements.Add(casES); ccsConnector.TrueStatements.Add(casEvent); ccsConnector.TrueStatements.Add(casHandler); ccsConnector.TrueStatements.Add(new CodeExpressionStatement(cmieAdd)); // Only add if statement at start of new scope if (!xamlClrEventNode.IsSameScope) { _ccRoot.StyleConnectorFn.Statements.Add(ccsConnector); } } } else { // // ((Foo)target).Bar += new BarEventHandler(OnBar); // // *or* // // ((Foo)target).AddHandler( Baz.BarEvent, new BarEventHandler(OnBar)); // CodeCastExpression cceTarget; Type eventTarget; // Create the markup event information MarkupEventInfo mei = new MarkupEventInfo( xamlClrEventNode.Value, // Event handler string xamlClrEventNode.EventName, // Event name string xamlClrEventNode.EventMember, // MemberInfo xamlClrEventNode.LineNumber); // LineNumber // Get the type that defines the event (e.g. typeof(Button) for Button.Clicked or typeof(Mouse) for Mouse.MouseMove) eventTarget = xamlClrEventNode.ListenerType; // Create the type cast expression "(Foo)target" cceTarget = new CodeCastExpression( eventTarget, careTarget); // Create the whole code statement (either in += form or in AddHandler form) CodeStatement csAddCLREvent = AddCLREvent( eventTarget, null, cceTarget, mei ); if (SwitchStatementSupported()) { _ccRoot.StyleConnectorFn.Statements.Add( csAddCLREvent ); } else { ccsConnector.TrueStatements.Add( csAddCLREvent ); // Only add if statement at start of new scope if (!xamlClrEventNode.IsSameScope) { _ccRoot.StyleConnectorFn.Statements.Add(ccsConnector); } } } }
/// <summary> /// 构造一个命名空间 /// </summary> /// <returns>code</returns> static CodeNamespace CreateMimsyNamespace() { // 定义命名空间 CodeNamespace mimsyNamespace = new CodeNamespace("Mimsy"); // 添加引用 mimsyNamespace.Imports.AddRange(new[] { new CodeNamespaceImport("System"), new CodeNamespaceImport("System.Text"), new CodeNamespaceImport("System.Collections") }); // 定义类 CodeTypeDeclaration jubjubClass = new CodeTypeDeclaration("Jubjub") { TypeAttributes = TypeAttributes.Public // NotPublic = internal, the internal type isn't visible to the dynamic binder }; // 定义成员字段 CodeMemberField wabeCountFld = new CodeMemberField(typeof(int), "_wabeCount") { Attributes = MemberAttributes.Private }; jubjubClass.Members.Add(wabeCountFld); // 附加字段到类 mimsyNamespace.Types.Add(jubjubClass); // 附加类到命名空间 // 定义实例构造函数 CodeConstructor jubjubCtor = new CodeConstructor { Attributes = MemberAttributes.Public }; // 定义参数 var para = new CodeParameterDeclarationExpression(typeof(int), "wabeCount"); jubjubCtor.Parameters.Add(para); // 附加参数到构造函数 // 添加 ArrayList 字段 var typerefArrayList = new CodeTypeReference("ArrayList"); CodeMemberField updatesFld = new CodeMemberField(typerefArrayList, "_updates"); jubjubClass.Members.Add(updatesFld); // 引用 _updates 字段 var refUpdatesFld = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_updates"); // 实例化 ArrayList var newArrayList = new CodeObjectCreateExpression(typerefArrayList); // 赋值 var assignUpdates = new CodeAssignStatement(refUpdatesFld, newArrayList); jubjubCtor.Statements.Add(assignUpdates); // 附加赋值语句到构造函数 // 引用 _wabeCount 字段 var refWabeCountFld = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_wabeCount"); // 定义引用属性(用于赋值时进行判断) var refWabeCountProp = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "WabeCount"); // 定义引用参数 var refWabeCountArg = new CodeArgumentReferenceExpression("wabeCount"); // 定义赋值语句 var assignWabeCount = new CodeAssignStatement(refWabeCountProp, refWabeCountArg); jubjubCtor.Statements.Add(assignWabeCount); // 附加赋值语句到构造函数 jubjubClass.Members.Add(jubjubCtor); // 附加构造函数到类 // 定义成员属性 CodeMemberProperty wabeCountProp = new CodeMemberProperty() { Attributes = MemberAttributes.Public | MemberAttributes.Final, // Final == Nonvirtual Type = new CodeTypeReference(typeof(int)), Name = "WabeCount" }; // 为属性添加 get 语句 wabeCountProp.GetStatements.Add(new CodeMethodReturnStatement(refWabeCountFld)); // 为属性添加 set 语句 var suppliedPropertyValue = new CodePropertySetValueReferenceExpression(); // value var zero = new CodePrimitiveExpression(0); var suppliedPropValIsLessThanZero = new CodeBinaryOperatorExpression(suppliedPropertyValue, CodeBinaryOperatorType.LessThan, zero); // if/else 语句进行赋值判断, CodeDOM 不支持三元运算表达式 (value < 0) ? 0 : value; var testSuppliedPropValAndAssign = new CodeConditionStatement(suppliedPropValIsLessThanZero, new CodeStatement[] { new CodeAssignStatement(refWabeCountFld,zero) }, new CodeStatement[] { new CodeAssignStatement(refWabeCountFld,suppliedPropertyValue) }); wabeCountProp.SetStatements.Add(testSuppliedPropValAndAssign); wabeCountProp.SetStatements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(refUpdatesFld, "Add"), refWabeCountFld)); jubjubClass.Members.Add(wabeCountProp); // 附加属性到类 // 定义一个方法 CodeMemberMethod methGetWabeCountHistory = new CodeMemberMethod { Attributes = MemberAttributes.Public | MemberAttributes.Final, Name = "GetWabeCountHistory", ReturnType = new CodeTypeReference(typeof(string)) }; jubjubClass.Members.Add(methGetWabeCountHistory); // 附加方法到类 // 定义本地变量并实例化 methGetWabeCountHistory.Statements.Add(new CodeVariableDeclarationStatement("StringBuilder", "result")); var refResultVar = new CodeVariableReferenceExpression("result"); methGetWabeCountHistory.Statements.Add(new CodeAssignStatement(refResultVar, new CodeObjectCreateExpression("StringBuilder"))); // 定义本地变量 ndx methGetWabeCountHistory.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "ndx")); // 引用本地变量 ndx var refNdxVar = new CodeVariableReferenceExpression("ndx"); #region 创建 for 语句 // 赋值语句 ndx = 0 var initNdxVar = new CodeAssignStatement(refNdxVar, new CodePrimitiveExpression(0)); // 条件语句 ndx < this._updates.Count var testNdxWithUpdatesCount = new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.LessThan, new CodePropertyReferenceExpression(refUpdatesFld, "Count")); // 自增语句 var incrementNdxVar = new CodeAssignStatement(refNdxVar, new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))); // 比较 if(ndx == 0) var compareNdxWithZero = new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)); // 方法调用 result.AppendFormat("{0}", this._updates[ndx]) var methAppendFormatInvoke = new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(refResultVar, "AppendFormat"), new CodePrimitiveExpression("{0}"), new CodeArrayIndexerExpression(refUpdatesFld, refNdxVar) ) ); // 方法调用 result.AppendFormat(", {0}", this._updates[ndx]) var methAppendFormtInvokeWithCommas = new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(refResultVar, "AppendFormat"), new CodePrimitiveExpression(", {0}"), new CodeArrayIndexerExpression(refUpdatesFld, refNdxVar) ) ); methGetWabeCountHistory.Statements.Add( new CodeIterationStatement(initNdxVar, testNdxWithUpdatesCount, incrementNdxVar, new CodeConditionStatement(compareNdxWithZero, new CodeStatement[] { methAppendFormatInvoke }, new CodeStatement[] { methAppendFormtInvokeWithCommas }))); #endregion // 定义返回值 methGetWabeCountHistory.Statements.Add( new CodeMethodReturnStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(refResultVar, "ToString")))); return mimsyNamespace; }
static void GenerateProjectActionsCode (CodeNamespace cns, GenerationOptions options, params ProjectBackend[] projects) { bool multiProject = projects.Length > 1; CodeTypeDeclaration type = new CodeTypeDeclaration ("ActionGroups"); type.Attributes = MemberAttributes.Private; type.TypeAttributes = TypeAttributes.NestedAssembly; cns.Types.Add (type); // Generate the global action group getter CodeMemberMethod met = new CodeMemberMethod (); met.Name = "GetActionGroup"; type.Members.Add (met); met.Parameters.Add (new CodeParameterDeclarationExpression (typeof(Type), "type")); if (multiProject) met.Parameters.Add (new CodeParameterDeclarationExpression (typeof(string), "file")); met.ReturnType = new CodeTypeReference (typeof(Gtk.ActionGroup)); met.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeMethodInvokeExpression call = new CodeMethodInvokeExpression ( new CodeMethodReferenceExpression ( new CodeTypeReferenceExpression (new CodeTypeReference (cns.Name + ".ActionGroups")), "GetActionGroup" ), new CodePropertyReferenceExpression ( new CodeArgumentReferenceExpression ("type"), "FullName" ) ); if (multiProject) call.Parameters.Add (new CodeArgumentReferenceExpression ("file")); met.Statements.Add (new CodeMethodReturnStatement (call)); // Generate the global action group getter (overload) met = new CodeMemberMethod (); met.Name = "GetActionGroup"; type.Members.Add (met); met.Parameters.Add (new CodeParameterDeclarationExpression (typeof(string), "name")); if (multiProject) met.Parameters.Add (new CodeParameterDeclarationExpression (typeof(string), "file")); met.ReturnType = new CodeTypeReference (typeof(Gtk.ActionGroup)); met.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeArgumentReferenceExpression cfile = new CodeArgumentReferenceExpression ("file"); CodeArgumentReferenceExpression cid = new CodeArgumentReferenceExpression ("name"); CodeStatementCollection projectCol = met.Statements; int n=1; foreach (ProjectBackend gp in projects) { CodeStatementCollection widgetCol; if (multiProject) { CodeConditionStatement pcond = new CodeConditionStatement (); pcond.Condition = new CodeBinaryOperatorExpression ( cfile, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression (gp.Id) ); projectCol.Add (pcond); widgetCol = pcond.TrueStatements; projectCol = pcond.FalseStatements; } else { widgetCol = projectCol; } foreach (Wrapper.ActionGroup grp in gp.ActionGroups) { string fname = "group" + (n++); CodeMemberField grpField = new CodeMemberField (new CodeTypeReference (typeof(Gtk.ActionGroup), CodeTypeReferenceOptions.GlobalReference), fname); grpField.Attributes |= MemberAttributes.Static; type.Members.Add (grpField); CodeFieldReferenceExpression grpVar = new CodeFieldReferenceExpression ( new CodeTypeReferenceExpression (new CodeTypeReference (cns.Name + ".ActionGroups", CodeTypeReferenceOptions.GlobalReference)), fname ); CodeConditionStatement pcond = new CodeConditionStatement (); pcond.Condition = new CodeBinaryOperatorExpression ( cid, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression (grp.Name) ); widgetCol.Add (pcond); // If the group has not yet been created, create it CodeConditionStatement pcondGrp = new CodeConditionStatement (); pcondGrp.Condition = new CodeBinaryOperatorExpression ( grpVar, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression (null) ); pcondGrp.TrueStatements.Add ( new CodeAssignStatement ( grpVar, new CodeObjectCreateExpression (grp.Name) ) ); pcond.TrueStatements.Add (pcondGrp); pcond.TrueStatements.Add (new CodeMethodReturnStatement (grpVar)); widgetCol = pcond.FalseStatements; } widgetCol.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (null))); } if (met.Statements.Count == 0) met.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (null))); }
private static void GenerateConstructors(Type t, CodeTypeDeclaration codeType) { CodeFieldReferenceExpression omObjectFieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), OmObject); ConstructorInfo[] constructors = t.GetConstructors(); ConstructorInfo publicParameterless = null; ConstructorInfo publicSystemParams = null; ConstructorInfo publicEnumParams = null; List<ConstructorInfo> publicGeneralParams = new List<ConstructorInfo>(); foreach (ConstructorInfo con in constructors.Where(c => c.IsPublic || c.IsStatic)) { ParameterInfo[] parameters = con.GetParameters(); if (parameters == null || parameters.Length == 0) { publicParameterless = con; } else if (con.IsStatic) { } else { publicGeneralParams.Add(con); } } if (publicParameterless != null) { CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; CodeObjectCreateExpression createExpression = new CodeObjectCreateExpression(t); constructor.Statements.Add(new CodeAssignStatement(omObjectFieldReference, createExpression)); codeType.Members.Add(constructor); } foreach (ConstructorInfo c in publicGeneralParams) { AddConstructorWithCopiedParameters(codeType, t, omObjectFieldReference, c); } // Default internal constructor that accepts the OM object to wrap CodeConstructor defaultConstructor = new CodeConstructor(); defaultConstructor.Attributes = MemberAttributes.Assembly; CodeParameterDeclarationExpression omObjectParameter = new CodeParameterDeclarationExpression(t, OmObject); defaultConstructor.Parameters.Add(omObjectParameter); CodeArgumentReferenceExpression omObjectArgumentReference = new CodeArgumentReferenceExpression(OmObject); CodeObjectCreateExpression createException = new CodeObjectCreateExpression(typeof(ArgumentNullException), new CodePrimitiveExpression(OmObject)); CodeThrowExceptionStatement throwException = new CodeThrowExceptionStatement(createException); CodeBinaryOperatorExpression nullCheck = new CodeBinaryOperatorExpression(omObjectArgumentReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)); // if the parameter is null, throw an exception defaultConstructor.Statements.Add(new CodeConditionStatement(nullCheck, throwException)); defaultConstructor.Statements.Add(new CodeAssignStatement(omObjectFieldReference, omObjectArgumentReference)); codeType.Members.Add(defaultConstructor); }
// CodeExpression public void Visit (CodeArgumentReferenceExpression o) { g.GenerateArgumentReferenceExpression (o); }
protected override void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e) { Output.Write("[CodeArgumentReferenceExpression: {0}]", e.ToString()); }
/* * Code Generation methods */ protected abstract void GenerateArgumentReferenceExpression (CodeArgumentReferenceExpression e);