/// <summary> /// Adds a class declaration to the namespace. /// </summary> /// <param name="name">Name of the class.</param> /// <param name="typeParameters">List of type parameters if the class is generic.</param> /// <returns>The class declaration instance that was added the namespace.</returns> public ClassDeclaration AddClass(string name, params string[] typeParameters) { ClassDeclaration result = new ClassDeclaration(this, name, typeParameters); result.IsPartial = false; _classes.Add(result); return result; }
protected override ClassDeclaration CreateClass(NamespaceDeclaration namespaceDeclaration, TableSchema table) { ClassDeclaration result = new ClassDeclaration(this.NameProvider.GetClassName(table.Name)); result.IsPartial = true; namespaceDeclaration.AddClass(result); return result; }
/// <summary> /// Adds a class declaration to the namespace. /// </summary> /// <param name="name">Name of the class.</param> /// <param name="isPartialClass">Indicates whether the class is partial or not.</param> /// <returns>The class declaration instance that was added to the namespace.</returns> public ClassDeclaration AddClass(string name, bool isPartialClass) { ClassDeclaration result = new ClassDeclaration(this, name); result.IsPartial = isPartialClass; _classes.Add(result); return result; }
/// <summary> /// Creates a ClassDeclaration. /// </summary> /// <param name="namespaceDeclaration">The NamespaceDeclaration instance the class is added to.</param> /// <param name="table">The database table the ClassDeclaration represents.</param> /// <returns>A reference to the ClassDeclaration instance that was created.</returns> protected override ClassDeclaration CreateClass(NamespaceDeclaration namespaceDeclaration, TableSchema table) { ClassDeclaration result = namespaceDeclaration.AddClass(this.NameProvider.GetClassName(table), true); ClassDeclaration baseType = new ClassDeclaration(this.ConfigOptions.BaseTypeName, new CodeDomTypeReference(result.FullName)); result.InheritsFrom(baseType); return result; }
public void CanCreateInterfaceWithTypeArgs() { InterfaceDeclaration iface = new InterfaceDeclaration("ITrackPropertyChanges", new CodeDomTypeReference("Awish.Common.Models.Core.Company")); ClassDeclaration cdecl = new ClassDeclaration("Company"); cdecl.Implements(iface); new CodeBuilder().GenerateCode(Console.Out, "Poops.McGee", cdecl); }
/// <summary> /// Creates a plain ol' property representing any column that is not a foreign key or primary key. /// </summary> /// <param name="classDeclaration">The class to which the property is added.</param> /// <param name="column">The column the property represents.</param> protected override void CreateNonKeyProperty(ClassDeclaration classDeclaration, ColumnSchema column) { string propertyName = this.NameProvider.GetPropertyName(column); string fieldName = this.NameProvider.GetFieldName(column); classDeclaration.AddProperty(propertyName, fieldName, column.DataType, column.Nullable) .AddAttribute("Castle.ActiveRecord.PropertyAttribute") .AddQuotedArgument(column.Name); }
protected override ClassDeclaration AddMethods(ClassDeclaration classDecl, TableSchema table) { AddToDataMethod(classDecl, table); AddFromDataMethod(classDecl, table); AddPropertyChangedPlumbing(classDecl); AddCopyToMethod(classDecl, table); return classDecl; }
private static bool HasDependencies(ClassDeclaration classDecl) { if (classDecl.Definition.BaseClass != null) { return classDecl.Definition.BaseClass.Symbol.SpecialType != SpecialType.System_Object; } return false; }
public void BasicClass() { var test = new ClassDeclaration("TestClass"); var expected = @"class TestClass { };"; Assert.AreEqual(expected, test.CreateSource()); }
/// <summary> /// Creates a property that is a foreign key within the current table that points to a primary key in another table. These typically have BelongsTo attributes. /// </summary> /// <param name="classDeclaration">The class to which the property is added.</param> /// <param name="foreignKey">The foreign key the property represents.</param> /// <returns>The foreign key property that was added.</returns> protected override PropertyDeclaration CreateForeignKey(ClassDeclaration classDeclaration, ForeignKeyColumnSchema foreignKey) { string fkname = this.NameProvider.GetPropertyName(foreignKey); string fkfieldname = this.NameProvider.GetFieldName(foreignKey); string fkdatatype = this.NameProvider.GetClassName(foreignKey.PrimaryKeyTable); PropertyDeclaration result = classDeclaration.AddProperty(fkname, fkfieldname, fkdatatype); result.AddAttribute("Castle.ActiveRecord.BelongsToAttribute").AddQuotedArgument(foreignKey.Name); return result; }
/// <summary> /// Creates a property that has a HasManyAttribute. /// </summary> /// <param name="classDecl">The class containing the property.</param> /// <param name="foreignkey">The foreign key to use.</param> /// <returns>A prpoerty with a hasmany attribute.</returns> protected override PropertyDeclaration CreateForeignKeyReference(ClassDeclaration classDecl, ForeignKeyColumnSchema foreignkey) { PropertyDeclaration fk = base.CreateForeignKeyReference(classDecl, foreignkey); if (fk == null) return null; AttributeDeclaration hasmany = fk.Attributes.Find(delegate(AttributeDeclaration attr) { return attr.TypeReference.IsTypeOf("Castle.ActiveRecord.HasManyAttribute"); }); if (hasmany != null) hasmany.AddArgument("Lazy=true, Inverse=false"); return fk; }
/// <summary> /// Creates a ClassDeclaration shell. /// </summary> /// <param name="nsdecl">NamespaceDeclaration the class is added.</param> /// <param name="table">Database table that the generated class will interact with.</param> /// <returns>The ClassDeclaration shell that was created.</returns> protected override ClassDeclaration CreateClass(NamespaceDeclaration nsdecl, TableSchema table) { ClassDeclaration result = nsdecl.AddClass(this.NameProvider.GetClassName(table), true); ClassDeclaration baseType = null; if (!String.IsNullOrEmpty(this.ConfigOptions.AbstractBaseName)) baseType = new ClassDeclaration(this.ConfigOptions.AbstractBaseName, new CodeDomTypeReference(result.FullName)); else baseType = new ClassDeclaration(this.ConfigOptions.BaseTypeName, new CodeDomTypeReference(result.FullName)); result.InheritsFrom(baseType); return result; }
/// <summary> /// Creates a ClassDeclaration. /// </summary> /// <param name="namespaceDeclaration">The NamespaceDeclaration instance the class is added to.</param> /// <param name="table">The database table the ClassDeclaration represents.</param> /// <returns> /// A reference to the ClassDeclaration instance that was created. /// </returns> protected override ClassDeclaration CreateClass(NamespaceDeclaration namespaceDeclaration, TableSchema table) { var result = namespaceDeclaration.AddClass(this.NameProvider.GetClassName(table), true); string baseTypeName = String.IsNullOrEmpty(ConfigOptions.AbstractBaseName) ? ConfigOptions.BaseTypeName : ConfigOptions.AbstractBaseName; var baseType = new ClassDeclaration(baseTypeName, new CodeDomTypeReference(result.FullName)); result.InheritsFrom(baseType); return result; }
/// <summary> /// Generates the specified writer. /// </summary> /// <param name="tableName">Name of the table.</param> /// <param name="nameField">The name field.</param> /// <param name="valueField">The value field.</param> public virtual ICodeDom<CodeTypeDeclaration> Generate(string tableName, string nameField, string valueField) { if (String.IsNullOrEmpty(tableName)) { throw new ArgumentException("tableName is null or empty.", "tableName"); } var tableSchema = _dbProvider.GetTableSchema(tableName); if (tableSchema == null) { throw new HyperActiveException("Table {0} was not found in the database. Check your spelling and make sure that's the table you wanted.", tableName); } string internalNameField = GetNameField(nameField, tableSchema); if (String.IsNullOrEmpty(internalNameField)) { return null; } string internalValueField = GetValueField(valueField, tableSchema); if (String.IsNullOrEmpty(internalValueField)) { return null; } var data = _dbProvider.GetTableEnumData(tableName, internalNameField, internalValueField); if (data.Count == 0) { return null; } var @enum = new ClassDeclaration(_nameProvider.GetEnumName(tableName)).InheritsFrom(typeof(Enumeration).FullName); var fieldType = new CodeTypeReference(typeof(EnumerationField)); foreach (var kvp in data) { var f1 = new CodeMemberField(fieldType, "_" + _nameProvider.GetEnumFieldName(kvp.Key)); f1.Attributes = MemberAttributes.Private | MemberAttributes.Static; f1.InitExpression = new CodeObjectCreateExpression(fieldType, new CodeSnippetExpression(kvp.Value.ToString()), new CodeSnippetExpression("\"" + _nameProvider.GetEnumFieldName(kvp.Key) + "\"")); @enum.Members.Add(f1); var p1 = new CodeMemberProperty(); p1.Type = fieldType; p1.Name = _nameProvider.GetEnumFieldName(kvp.Key); p1.Attributes = MemberAttributes.Public | MemberAttributes.Static; p1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, "_" + _nameProvider.GetEnumFieldName(kvp.Key)))); @enum.Members.Add(p1); } return @enum; }
public void MemberField() { var test = new ClassDeclaration("TestClass"); test.Fields.Add(new FieldDeclaration("m_someInt", Primitive.Int, AccessLevel.Private)); var expected = @"class TestClass { private: int m_someInt; };"; Assert.AreEqual(expected, test.CreateSource()); }
public void MemberFunction() { var test = new ClassDeclaration("TestClass"); test.Functions.Add(new FunctionDeclaration("DoSomething", Primitive.Char.MakePointer().MakeConst(), AccessLevel.Public)); var expected = @"class TestClass { public: const char *DoSomething(); };"; Assert.AreEqual(expected, test.CreateSource()); }
private void ValidateBaseClass(ClassDeclaration originalDecl, ClassDefinition classDef) { if (classDef.Constructors.Any(c => !c.Symbol.IsImplicitlyDeclared) || classDef.Methods.Any(m => !m.Symbol.IsImplicitlyDeclared) || classDef.Properties.Any(p => p.MemberKind != MemberDefinitionKind.Field) || classDef.Fields.Any(f => f.MemberKind != MemberDefinitionKind.Field)) { throw new CompilationException("A class using the [ScriptObjectLiteral] attribute cannot inherit from class " + classDef.Symbol.GetFullName() + ", because it contains one or more declarations that are not compatible with object literal notations.", originalDecl); } if (classDef.BaseClass != null && classDef.BaseClass.Symbol.SpecialType != Roslyn.Compilers.SpecialType.System_Object) ValidateBaseClass(originalDecl, classDef.BaseClass); }
public void Test() { ClassDeclaration cdecl = new ClassDeclaration("ResultSet"); MethodDeclaration mdecl = cdecl.AddMethod("GetData", typeof(DataTable)) .Public() .AddParameter(typeof(string), "name"); mdecl.Declare("result").New(new CodeDomTypeReference(typeof(DataTable))); mdecl.Declare("columns") .As(typeof(DataColumnCollection)) .Assign("result", "Columns"); mdecl.Call("columns", "Add").With("typeof(string)", "\"name\""); new CodeBuilder().GenerateCode(Console.Out, "My.Data", cdecl); }
public void CSharpCodeGenerator_Constructor() { var type = new ClassDeclaration("Sample"); var ctor = type.AddMember(new ConstructorDeclaration()); ctor.Modifiers = Modifiers.Internal; var generator = new CSharpCodeGenerator(); var result = generator.Write(type); Assert.That.StringEquals(@"class Sample { internal Sample() { } } ", result); }
private static MethodDeclaration GenerateExplicitImplementationMethod(ClassDeclaration clientClass, InterfaceDeclaration clientInterface, Method method, TypeReference requestType) { var m = clientClass.AddMember(new MethodDeclaration(GetMethodName(method))); m.PrivateImplementationType = clientInterface; GenerateMethodSignature(method, m, requestType, out _, out _, out _); foreach (var arg in m.Arguments) { arg.DefaultValue = null; } m.Statements = new ReturnStatement( new MethodInvokeExpression( new MemberReferenceExpression(new ThisExpression(), method.MethodGroup.Name + '_' + m.Name), m.Arguments.Select(arg => new ArgumentReferenceExpression(arg)).ToArray())); return(m); }
private static void ProcessAttributeUsage(this AttributeUsage attributeUsage) { ClassDeclaration classDeclaration = attributeUsage.Scope.GlobalClassSearch(attributeUsage.Name.Name); if (classDeclaration == null) { throw new ScopeException($"Attribute {attributeUsage.Name.Name} was not found"); } if (!classDeclaration.IsAttribute) { throw new ScopeException($"Class {attributeUsage.Name.Name} is not an attribute"); } AttributeDeclaration attributeDeclarationClass = classDeclaration.CastTo <AttributeDeclaration>(); CheckCallParameters(attributeUsage, attributeUsage.FunctionCallParameters, attributeDeclarationClass.ParameterNodes); }
/// <summary> /// Creates a property that has many children that point to the primary key contained within this class. Typically these will have HasMany attributes. /// </summary> /// <param name="classDeclaration">The class to which the property is added.</param> /// <param name="foreignKey">The foreign key in the table that references the primary key in this class.</param> /// <returns>The property that was added.</returns> protected override PropertyDeclaration CreateForeignKeyReference(ClassDeclaration classDeclaration, ForeignKeyColumnSchema foreignKey) { if (foreignKey.Table.PrimaryKey == null) return null; string propertyName = this.NameProvider.GetListPropertyName(foreignKey); string fieldName = this.NameProvider.GetListFieldName(foreignKey); string typeParam = this.NameProvider.GetClassName(foreignKey.Table); CodeDomTypeReference genericList = new CodeDomTypeReference("System.Collections.Generic.List").AddTypeParameters(typeParam); PropertyDeclaration result = classDeclaration.AddProperty(propertyName, fieldName, "System.Collections.Generic.IList"); result.InitializeField(genericList) .AddTypeParameter(typeParam) .AddAttribute("Castle.ActiveRecord.HasManyAttribute") .AddArgument("typeof(" + this.NameProvider.GetClassName(foreignKey.Table) + ")"); return result; }
protected override async Task <ClassDeclaration> AssignUpsertedReferences(ClassDeclaration record) { record.AttributeListCollection = await _attributeLists.UpsertAsync(record.AttributeListCollection); record.AttributeListCollectionId = record.AttributeListCollection?.AttributeListCollectionId ?? record.AttributeListCollectionId; record.BaseList = await _baseLists.UpsertAsync(record.BaseList); record.BaseListId = record.BaseList?.BaseListId ?? record.BaseListId; record.ConstraintClauseList = await _constraintClauseLists.UpsertAsync(record.ConstraintClauseList); record.ConstraintClauseListId = record.ConstraintClauseList?.ConstraintClauseListId ?? record.ConstraintClauseListId; record.ConstructorList = await _constuctorLists.UpsertAsync(record.ConstructorList); record.ConstructorListId = record.ConstructorList?.ConstructorListId ?? record.ConstructorListId; record.DocumentationCommentList = await _documentationCommentLists.UpsertAsync(record.DocumentationCommentList); record.DocumentationCommentListId = record.DocumentationCommentList?.DocumentationCommentListId ?? record.DocumentationCommentListId; record.FieldList = await _fieldLists.UpsertAsync(record.FieldList); record.FieldListId = record.FieldList?.FieldListId ?? record.FieldListId; record.Finalizer = await _finalizers.UpsertAsync(record.Finalizer); record.FinalizerId = record.Finalizer?.FinalizerId ?? record.FinalizerId; record.Identifier = await _identifiers.UpsertAsync(record.Identifier); record.IdentifierId = record.Identifier?.IdentifierId ?? record.IdentifierId; record.MethodList = await _methodLists.UpsertAsync(record.MethodList); record.MethodListId = record.MethodList?.MethodListId ?? record.MethodListId; record.ModifierList = await _modifierLists.UpsertAsync(record.ModifierList); record.ModifierListId = record.ModifierList?.ModifierListId ?? record.ModifierListId; record.Namespace = await _namespaces.UpsertAsync(record.Namespace); record.NamespaceId = record.Namespace?.NamespaceId ?? record.NamespaceId; record.PropertyList = await _propertyLists.UpsertAsync(record.PropertyList); record.PropertyListId = record.PropertyList?.PropertyListId ?? record.PropertyListId; record.TypeParameterList = await _typeParameterLists.UpsertAsync(record.TypeParameterList); record.TypeParameterListId = record.TypeParameterList?.TypeParameterListId ?? record.TypeParameterListId; record.UsingDirectiveList = await _usingDirectiveLists.UpsertAsync(record.UsingDirectiveList); record.UsingDirectiveListId = record.UsingDirectiveList?.UsingDirectiveListId ?? record.UsingDirectiveListId; return(record); }
private IList <Mutant> GetMethodMutants(string method) { var methodSyntax = _class .DescendantNodes <MethodDeclarationSyntax>() .FirstOrDefault(x => x.MethodName() == method); if (methodSyntax != null) { var mutantOrchestrator = new MutantOrchestrator(); var syntaxNodeAnalysisFactory = new SyntaxNodeAnalysisFactory(); var classDeclaration = new ClassDeclaration(_class); var syntaxNodeAnalysis = syntaxNodeAnalysisFactory.Create(methodSyntax, classDeclaration); mutantOrchestrator.Mutate(syntaxNodeAnalysis); return(mutantOrchestrator.GetLatestMutantBatch().ToList()); } return(new List <Mutant>()); }
public void TestRootedAndUnrooted() { ModuleDeclaration module = ReflectToModules("public class Foo { } ", "SomeModule").Find(m => m.Name == "SomeModule"); ClassDeclaration fooClass = module.AllClasses.Where(cl => cl.Name == "Foo").FirstOrDefault(); Assert.IsNotNull(fooClass); Assert.IsFalse(fooClass.IsUnrooted); ClassDeclaration unrootedFoo = fooClass.MakeUnrooted() as ClassDeclaration; Assert.IsNotNull(unrootedFoo); Assert.IsTrue(unrootedFoo != fooClass); Assert.AreEqual(unrootedFoo.Name, fooClass.Name); Assert.AreEqual(unrootedFoo.Access, fooClass.Access); ClassDeclaration doubleUnrootedFoo = unrootedFoo.MakeUnrooted() as ClassDeclaration; Assert.IsNotNull(doubleUnrootedFoo); Assert.IsTrue(doubleUnrootedFoo == unrootedFoo); }
private static void PreProcess(this ClassDeclaration classDeclaration) { var scope = classDeclaration.Scope; var duplicatedModifiers = classDeclaration.ModifiersList .GetDuplicatedItems().ToList(); if (duplicatedModifiers.Any()) { throw new ScopeException($"Modifier {duplicatedModifiers.First()} was specified more than once"); } classDeclaration.ModifiersList.ForEach(modifier => { if (modifier == Modifier.Static) { classDeclaration.IsStatic = true; } if (modifier == Modifier.Extern) { classDeclaration.IsExtern = true; } }); if (!classDeclaration.IsStatic && !classDeclaration.IsAttribute) { throw new ScopeException( $"Only static classes are supported at the moment ({classDeclaration.Name})"); } classDeclaration.FunctionDeclarationNodes .ForEach(functionDeclaration => { functionDeclaration.CheckName(scope); scope.AddFunction(functionDeclaration); functionDeclaration.PreProcess(); }); classDeclaration.VarDeclarationNodes .ForEach(declaration => { declaration.CheckName(scope); scope.AddVariable(declaration); }); }
protected override PropertyDeclaration CreateForeignKey(ClassDeclaration classDeclaration, ForeignKeyColumnSchema foreignKey) { string columnName = foreignKey.PrimaryKeyTable.Name; string fkname = this.NameProvider.GetPropertyName(columnName); string fkfieldname = this.NameProvider.GetFieldName(columnName); string fkdatatype = this.NameProvider.GetClassName(foreignKey.PrimaryKeyTable); //add the field var field = new CodeMemberField(fkdatatype, fkfieldname); classDeclaration.Members.Add(field); //add the prop var prop = new CodeMemberProperty(); prop.Name = fkname; prop.Type = new CodeTypeReference(fkdatatype); prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fkfieldname))); //if (value == null || this._stateCode == null || (value.ID != this._stateCode.ID)) var ifValueNull = new CodeBinaryOperatorExpression(new CodeSnippetExpression("value"), CodeBinaryOperatorType.IdentityEquality, new CodeSnippetExpression("null")); var ifFieldNull = new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fkfieldname), CodeBinaryOperatorType.IdentityEquality, new CodeSnippetExpression("null")); var valueIdExpression = new CodePropertyReferenceExpression(new CodeSnippetExpression("value"), "ID"); var fieldIdExpression = new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fkfieldname), "ID"); var ifValueIdDoesNotEqualFieldId = new CodeBinaryOperatorExpression(valueIdExpression, CodeBinaryOperatorType.IdentityInequality, fieldIdExpression); prop.SetStatements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression(ifValueNull, CodeBinaryOperatorType.BooleanOr, ifFieldNull), CodeBinaryOperatorType.BooleanOr, ifValueIdDoesNotEqualFieldId), new CodeSnippetStatement(String.Format("{1}((EightyProofSolutions.BlogEngine.Core.Models.ITrackPropertyChanges)this).OnPropertyChanged(\"{0}\", this.{2}, value);", fkname, new String('\t', 5), fkfieldname)), new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fkfieldname), new CodeSnippetExpression("value")))); classDeclaration.Members.Add(prop); return null; //PropertyDeclaration result = classDeclaration.AddProperty(fkname, fkfieldname, fkdatatype); //return result; }
public void NoDatabaseSchemaWhileClassDeclarationTest() { Mock <IStorage> storage = new Mock <IStorage>(); storage.Setup(s => s.SaveSchema(It.IsAny <IDatabaseSchema>())).Verifiable(); Mock <Action <String, MessageLevel> > log = new Mock <Action <String, MessageLevel> >(); ClassDeclaration classDeclarationStatement = new ClassDeclaration(); QueryParameters parameters = new QueryParameters { Storage = storage.Object, Log = log.Object }; var result = classDeclarationStatement.Execute(parameters); storage.Verify(s => s.SaveSchema(It.IsAny <IDatabaseSchema>()), Times.Never); Assert.AreEqual(ResultType.StringResult, result.Result.QueryResultType); Assert.AreEqual("Error ocured while class creation", result.Result.StringOutput); }
private void convertClassDeclaration(ClassDeclarationSyntax classDeclarationSyntax, ModuleDeclaration module) { var classDeclaration = new ClassDeclaration(); module.Clases.Add(classDeclaration); foreach (var memberDeclarationSyntax in classDeclarationSyntax.Members) { if (memberDeclarationSyntax is PropertyDeclarationSyntax propertyDeclaration) { convertPropertyDeclaration(propertyDeclaration, classDeclaration); } if (memberDeclarationSyntax is MethodDeclarationSyntax method) { convertMethodDeclaration(method, classDeclaration); } } }
/// <summary> /// Génére le code d'une classe. /// </summary> /// <param name="declaration"></param> /// <returns></returns> string GenerateClass(ClassDeclaration declaration) { StringBuilder builder = new StringBuilder(); string inheritance = declaration.InheritsFrom == null ? "" : "(" + declaration.InheritsFrom + ")"; builder.Append("class " + declaration.Name); // Héritage builder.AppendLine(inheritance + ":\n"); // Instructions foreach (Instruction instruction in declaration.Instructions) { builder.Append(Tools.StringUtils.Indent(GenerateInstruction(instruction), 1)); builder.Append("\n"); } return(builder.ToString()); }
/// <summary> /// Adds compiler feature abstraction to all attribute annotations of or nested within a class declaration. /// </summary> /// <param name="class">The class declaration</param> private static void AddCompilerAbstractionToAttributes(ClassDeclaration @class) { foreach (ConditionalAttributeAnnotation annotation in @class.AttributeAnnotations) { AddCompilerAbstraction(annotation); } foreach (ClassDeclarationNestedDeclaration declaration in @class.NestedDeclarations) { if (declaration.DeclarationCase == ClassDeclarationNestedDeclaration.DeclarationOneofCase.NestedTypeDeclaration && declaration.NestedTypeDeclaration.DeclarationCase == NestedTypeDeclaration.DeclarationOneofCase.ClassDeclaration) { AddCompilerAbstractionToAttributes(declaration.NestedTypeDeclaration.ClassDeclaration); } if (declaration.DeclarationCase == ClassDeclarationNestedDeclaration.DeclarationOneofCase.Member) { AddCompilerAbstractionToAttributes(declaration.Member); } } }
public void ClassAlreadyExistsTest() { var existingClass = new Class { ClassId = new ClassId { Id = 1, Name = "Test1" }, Name = "Test1" }; var classes = new ConcurrentDictionary <ClassId, Class>(); classes.TryAdd(existingClass.ClassId, existingClass); Mock <IDatabaseParameters> database = new Mock <IDatabaseParameters>(); database.Setup(d => d.Schema.Classes).Returns(classes); Mock <IStorage> storage = new Mock <IStorage>(); storage.Setup(s => s.SaveSchema(It.IsAny <IDatabaseSchema>())).Verifiable(); Mock <Action <String, MessageLevel> > log = new Mock <Action <String, MessageLevel> >(); ClassDeclaration classDeclarationStatement = new ClassDeclaration(); Mock <ClassName> className = new Mock <ClassName>(); className.Setup(cn => cn.Execute(It.IsAny <QueryParameters>())).Returns(new QueryDTO { QueryClass = existingClass }); classDeclarationStatement.Add(className.Object); QueryParameters parameters = new QueryParameters { Database = database.Object, Storage = storage.Object, Log = log.Object }; var result = classDeclarationStatement.Execute(parameters); storage.Verify(s => s.SaveSchema(It.IsAny <IDatabaseSchema>()), Times.Never); Assert.AreEqual(ResultType.StringResult, result.Result.QueryResultType); Assert.AreEqual("Class or interface with name: " + existingClass.Name + " arleady exists!", result.Result.StringOutput); }
private void AddField(ClassDeclaration c, FieldInfo f) { if (c == null) { throw new ArgumentNullException("c"); } if (f == null) { throw new ArgumentNullException("f"); } FieldDeclaration fd = c.AddField(MapType(f.FieldType), f.Name); PropertyDeclaration p = c.AddProperty(fd, f.Name, true, true, false); // adding attributes if (TypeHelper.HasCustomAttribute(f, typeof(XmlAttributeAttribute))) { XmlAttributeAttribute att = (XmlAttributeAttribute)TypeHelper.GetFirstCustomAttribute(f, typeof(XmlAttributeAttribute)); AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlAttributeAttribute)); string attrName = att.AttributeName; if (att.AttributeName.Length == 0) { attrName = f.Name; } AttributeArgument arg = attr.Arguments.Add( "AttributeName", Expr.Prim(attrName) ); } else { if (TypeHelper.HasCustomAttribute(f, typeof(XmlElementAttribute))) { AttachXmlElementAttributes(p, f); } else { AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlElementAttribute)); attr.Arguments.Add("ElementName", Expr.Prim(f.Name)); } } }
public static bool IsClassAndSuperclassesContainsLoop(this ClassDeclaration classDecl, HashSet <MofProduction> mof) { Func <MofProduction, bool> func = null; while (classDecl != null && classDecl.SuperclassName != null) { HashSet <MofProduction> mofProductions = mof; if (func == null) { func = (MofProduction item) => item.GetFullClassName() == classDecl.SuperclassName.FullName; } var temp = mofProductions.First <MofProduction>(func) as ClassDeclaration; if (classDecl != temp) { continue; } return(true); } return(false); }
CSProperty ImportProperty(PropertyDefinition property, ClassDeclaration typeDeclaration, bool isProtocol) { var hasGetter = property.GetMethod != null; var hasSetter = property.SetMethod != null; if (!hasGetter && !hasGetter) { return(null); } // if there's a getter, it's the return value's type // if there's a setter, it's the 0th argument (value) var gettervisibility = ToVisibility(property.GetMethod ?? property.SetMethod); var settervisibility = ToVisibility(property.SetMethod ?? property.GetMethod); var propType = property.GetMethod != null?MapType(property.GetMethod.ReturnType) : MapType(property.SetMethod.Parameters [0].ParameterType); return(new CSProperty(propType, ToMethodKind(property.GetMethod ?? property.SetMethod), new CSIdentifier(property.Name), gettervisibility, hasGetter ? new CSCodeBlock() : null, settervisibility, hasSetter ? new CSCodeBlock() : null)); }
public void CSharpCodeGenerator_Constructor_ThisWithArgs() { var type = new ClassDeclaration("Sample"); var ctor = type.AddMember(new ConstructorDeclaration()); ctor.Initializer = new ConstructorThisInitializer(new LiteralExpression("arg")); ctor.Modifiers = Modifiers.Public; var generator = new CSharpCodeGenerator(); var result = generator.Write(type); Assert.That.StringEquals(@"class Sample { public Sample() : this(""arg"") { } } ", result); }
private void ValidateBaseClass(ClassDeclaration originalDecl, ClassDefinition classDef) { var extensionFactory = new ExtensionFactory(); var extensions = extensionFactory.GetExtensions(classDef.Symbol); if (!extensions.Any(e => e.GetType() == typeof(ScriptObjectLiteralExtension)) && (classDef.Constructors.Any(c => !c.Symbol.IsImplicitlyDeclared) || classDef.Methods.Any(m => !m.Symbol.IsImplicitlyDeclared) || classDef.Properties.Any(p => p.MemberKind != MemberDefinitionKind.Field) || classDef.Fields.Any(f => f.MemberKind != MemberDefinitionKind.Field))) { throw new CompilationException("A class using the [ScriptObjectLiteral] attribute cannot inherit from class " + classDef.Symbol.GetFullName() + ", because it contains one or more declarations that are not compatible with object literal notations.", originalDecl); } if (classDef.BaseClass != null && classDef.BaseClass.Symbol.SpecialType != Roslyn.Compilers.SpecialType.System_Object) { ValidateBaseClass(originalDecl, classDef.BaseClass); } }
private void AddPropertyInitStatements(Constructor ctorNode) { ClassDeclaration classNode = ctorNode.Parent as ClassDeclaration; if (classNode == null) { return; } Block ctorBlock = ctorNode.Body as Block; List <PropertyDeclaration> props = this.GetInitProperties(classNode); props.Reverse(); foreach (PropertyDeclaration prop in props) { ExpressionStatement statement = (ExpressionStatement)NodeHelper.CreateNode(this.BuildPropertyStatementString(prop.Name.Text)); (statement.Expression as BinaryExpression).SetRight(prop.Initializer, false); ctorBlock.InsertStatement(0, statement); } }
public void Generate(System.Extensions.CodeDom.NamespaceDeclaration ns) { if (this.Name == null) { throw new InvalidOperationException("name not set"); } // create class ClassDeclaration c = ns.AddClass(DecorateName(this.Name)); this.Properties = new Hashtable(); // add fields and properties foreach (DictionaryEntry de in this.Fields) { FieldDeclaration f = c.AddField(de.Value.ToString(), de.Key.ToString()); PropertyDeclaration p = c.AddProperty(f, true, !ReadOnly, false); this.Properties.Add(de, p); } }
private void GenerateClassType(Type t) { ClassDeclaration c = this.ns.Classes[this.conformer.ToCapitalized(t.Name)]; // generate fields and properties foreach (FieldInfo f in t.GetFields()) { if (f.FieldType.IsArray) { AddArrayField(c, f); } else { AddField(c, f); } } // add constructors GenerateDefaultConstructor(c); }
private static void TestRetrieveBaseClassName(ClassDeclarationSyntax classDeclarationNode, SemanticModel semanticModel, string expected) { Assert.IsNotNull(classDeclarationNode, "Found node should be of type `{0}`!", typeof(ClassDeclarationSyntax).Name); ClassDeclaration classDeclaration = new ClassDeclaration(classDeclarationNode, semanticModel); BaseTypeReference baseClass = classDeclaration.BaseClass; if (expected == null) { Assert.IsNull(baseClass, "Class name should be null!"); return; } string name = classDeclaration.BaseClass.Name; Assert.IsNotNull(name, "Class name should not be null!"); Assert.AreNotEqual(string.Empty, name, "Class name should not be empty!"); Assert.AreEqual(expected, name, "Base class name is not the one in source!"); }
private void ValidateClass(ClassDeclaration classDecl) { if (classDecl.IsStatic) throw new CompilationException("A class using the [ScriptObjectLiteral] attribute cannot be declaraed static.", classDecl); if (classDecl.Constructors.Count > 0) throw new CompilationException("A class using the [ScriptObjectLiteral] attribute cannot contain constructors.", classDecl); if (classDecl.Methods.Count > 0) throw new CompilationException("A class using the [ScriptObjectLiteral] attribute cannot contain methods.", classDecl); if (classDecl.Events.Count > 0) throw new CompilationException("A class using the [ScriptObjectLiteral] attribute cannot contain events.", classDecl); if (classDecl.Properties.Any(p => !p.IsAutoProperty)) throw new CompilationException("A class using the [ScriptObjectLiteral] attribute can only contain auto properties.", classDecl); if (classDecl.IsDerived) ValidateBaseClass(classDecl, classDecl.Definition.BaseClass); }
/// <summary> /// Génère un constructeur initialisant tous les champs bien comme il faut. /// </summary> /// <param name="decl"></param> /// <returns></returns> public string GenerateConstructor(ClassDeclaration decl) { StringBuilder b = new StringBuilder(); b.AppendLine(decl.Name + "::" + decl.Name + "() {"); /*var varDecls = decl.Instructions.Where(inst => inst is VariableDeclarationInstruction).ToList(); * * foreach (var vdecl in varDecls) * { * var d = vdecl as VariableDeclarationInstruction; * if (d.Var.Type.BaseType.JType == JSONType.Array || d.Var.Type.BaseType.JType == JSONType.Object) * { * b.AppendLine("\t" + d.Var.Name + " = " + GenerateTypeInstanceName(d.Var.Type) + "();"); * } * }*/ b.AppendLine("}"); return(b.ToString()); }
private void AddLostConstructor(ClassDeclaration classNode) { Constructor constructor = classNode.GetConstructor(); List <ClassDeclaration> baseClasses = classNode.Project.GetInheritClasses(classNode); if (constructor == null) { if (baseClasses.Count > 0) { var baseClass = baseClasses.Find(c => { var ctor = c.GetConstructor(); return(ctor != null && ctor.Parameters.Count > 0); }); if (baseClass != null) { Constructor baseCtor = baseClass.GetConstructor(); Constructor newCtor = (Constructor)NodeHelper.CreateNode((JObject)baseCtor.TsNode.DeepClone()); CallExpression baseNode = (CallExpression)NodeHelper.CreateNode(NodeKind.CallExpression); baseNode.SetExpression(NodeHelper.CreateNode(NodeKind.SuperKeyword)); foreach (Parameter parameter in baseCtor.Parameters) { baseNode.AddArgument(NodeHelper.CreateNode(NodeKind.Identifier, parameter.Name.Text)); } newCtor.SetBase(baseNode); newCtor.Body.ClearStatements(); ModifierNormalizer.NormalizeModify(newCtor); classNode.InsertMember(0, newCtor); } } else if (this.GetInitProperties(classNode).Count > 0) { Constructor newCtor = (Constructor)NodeHelper.CreateNode(BuildConstructorString()); ModifierNormalizer.NormalizeModify(newCtor); classNode.InsertMember(0, newCtor); } } }
public void DeclareClass(ClassDeclaration classNode, ModuleBuilder module) { if (classNode.IsAttribute) { return; } TypeBuilder typeBuilder = null; if (!classNode.IsExtern) { // create public static class typeBuilder = module.DefineType(classNode.Name, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Abstract); classTypeBuilders.Add(classNode.Name, typeBuilder); if (classNode.VarDeclarationNodes.Count > 0) { ConstructorBuilder constructor = typeBuilder.DefineConstructor( MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new Type[0]); ILGenerator ilGenerator = constructor.GetILGenerator(); foreach (var declarationNode in classNode.VarDeclarationNodes) { DeclareField(declarationNode, typeBuilder, ilGenerator); } ilGenerator.Emit(OpCodes.Ret); } } foreach (var funcNode in classNode.FunctionDeclarationNodes) { DeclareFunc(funcNode, typeBuilder); } }
public override void Generate() { if (this.Name == null) { throw new InvalidOperationException("name not set"); } // create class ClassDeclaration c = this.NamespaceDeclaration.AddClass(this.DataName); this.Properties = new Hashtable(); // add fields and properties foreach (DictionaryEntry de in this.Fields) { FieldDeclaration f = c.AddField(de.Value.ToString(), de.Key.ToString()); PropertyDeclaration p = c.AddProperty(f, true, !ReadOnly, false); this.Properties.Add(de, p); } this.Compile(); }
public void CSharpCodeGenerator_FieldDeclaration() { var type = new ClassDeclaration("Sample"); type.AddMember(new FieldDeclaration("_a", typeof(int))); type.AddMember(new FieldDeclaration("_b", typeof(Type), Modifiers.Private)); type.AddMember(new FieldDeclaration("_c", typeof(int), Modifiers.Protected, 10)); var generator = new CSharpCodeGenerator(); var result = generator.Write(type); Assert.That.StringEquals(@"class Sample { int _a; private System.Type _b; protected int _c = 10; } ", result); }
/// <summary> /// Génére le code d'une classe. /// </summary> /// <param name="declaration"></param> /// <returns></returns> string GenerateClass(ClassDeclaration declaration) { StringBuilder builder = new StringBuilder(); string inheritance = declaration.InheritsFrom == null ? "" : " : " + declaration.InheritsFrom; if (declaration.Modifiers.Contains("public")) { builder.Append("public "); } builder.Append("class " + declaration.Name); // Paramètres génériques if (declaration.GenericParameters.Count > 0) { builder.Append("<"); foreach (string tupe in declaration.GenericParameters) { builder.Append(tupe); if (tupe != declaration.GenericParameters.Last()) { builder.Append(","); } } builder.Append(">"); } // Héritage builder.AppendLine(inheritance + "\n{\n"); // Instructions foreach (Instruction instruction in declaration.Instructions) { builder.Append(Tools.StringUtils.Indent(GenerateInstruction(instruction), 1)); builder.Append("\n"); } builder.AppendLine(Tools.StringUtils.Indent(GenerateDeserializer(declaration))); builder.Append("}"); return(builder.ToString()); }
private void CreateClass(Type t) { ClassDeclaration c = this.ns.AddClass(this.conformer.ToCapitalized(t.Name)); // check if XmlType present if (TypeHelper.HasCustomAttribute(t, typeof(XmlTypeAttribute))) { XmlTypeAttribute typeAttr = (XmlTypeAttribute)TypeHelper.GetFirstCustomAttribute(t, typeof(XmlTypeAttribute)); AttributeDeclaration type = c.CustomAttributes.Add(typeof(XmlTypeAttribute)); type.Arguments.Add("IncludeInSchema", Expr.Prim(typeAttr.IncludeInSchema)); if (this.Config.KeepNamespaces) { type.Arguments.Add("Namespace", Expr.Prim(typeAttr.Namespace)); } type.Arguments.Add("TypeName", Expr.Prim(typeAttr.TypeName)); } // check if XmlRoot present if (TypeHelper.HasCustomAttribute(t, typeof(XmlRootAttribute))) { XmlRootAttribute rootAttr = (XmlRootAttribute)TypeHelper.GetFirstCustomAttribute(t, typeof(XmlRootAttribute)); AttributeDeclaration root = c.CustomAttributes.Add(typeof(XmlRootAttribute)); root.Arguments.Add("ElementName", Expr.Prim(rootAttr.ElementName)); root.Arguments.Add("IsNullable", Expr.Prim(rootAttr.IsNullable)); if (this.Config.KeepNamespaces) { root.Arguments.Add("Namespace", Expr.Prim(rootAttr.Namespace)); } root.Arguments.Add("DataType", Expr.Prim(rootAttr.DataType)); } else { AttributeDeclaration root = c.CustomAttributes.Add(typeof(XmlRootAttribute)); root.Arguments.Add("ElementName", Expr.Prim(t.Name)); } this.types.Add(t, c); }
public override IQueryElement VisitClass_delcaration([NotNull] QueryGrammarParser.Class_delcarationContext context) { ClassDeclaration classDeclaration = new ClassDeclaration(); IQueryElement className = Visit(context.class_name()); classDeclaration.Add(className); if (context.parent_type() != null) { IQueryElement parentClasses = Visit(context.parent_type()); classDeclaration.Add(parentClasses); } foreach (var attribute in context.cls_attribute_dec_stm()) { IQueryElement attributeDeclaration = Visit(attribute); classDeclaration.Add(attributeDeclaration); } return(classDeclaration); }
private static void __Execute(atom.Trace context, int level, ClassDeclaration data, string file, bool isShowPrivate) { if (__IsEnabled(data, isShowPrivate)) { context. SetComment(__GetType(data, "class"), "[[[Data Type]]]"). SetUrl(file, __GetLine(data, data.Name.Pos.Value), __GetPosition(data, data.Name.Pos.Value)). Send(NAME.SOURCE.PREVIEW, NAME.TYPE.CLASS, level, __GetName(data.Name, true)); foreach (var a_Context in data.Members.OfType <MethodDeclaration>()) { __Execute(context, level + 1, a_Context, file, false, isShowPrivate); } foreach (var a_Context in data.Members.OfType <PropertyDeclaration>()) { __Execute(context, level + 1, a_Context, file, isShowPrivate); } foreach (var a_Context in data.Members.OfType <VariableDeclaration>()) { __Execute(context, level + 1, a_Context, file, isShowPrivate); } } }
protected override void CreateAssociationProperties(ClassDeclaration classDeclaration, TableSchema table) { if (classDeclaration == null || table == null || table.Associations.Count == 0) return; foreach (var assocTable in table.Associations) { Console.WriteLine("assocTable.Name=" + assocTable.Name); var otherTable = assocTable.ForeignKeys.Single(fk => { return fk.PrimaryKeyTable.Name != table.Name; }).PrimaryKeyTable; string propName = Inflector.Pluralize(this.NameProvider.GetPropertyName(otherTable.Name)); string fieldName = Inflector.Pluralize(this.NameProvider.GetFieldName(otherTable.Name)); var typeRef = new CodeDomTypeReference(typeof(IList<>).FullName, this.NameProvider.GetClassName(otherTable)); var prop = classDeclaration.AddProperty(propName, fieldName, typeRef); prop.AddAttribute("Castle.ActiveRecord.HasAndBelongsToMany") .AddArgument("typeof(" + this.NameProvider.GetClassName(otherTable) + ")") .AddQuotedArgument("Table", assocTable.Name) .AddQuotedArgument("ColumnKey", assocTable.ForeignKeys.Single(fk => { return fk.PrimaryKeyTable.Name == table.Name; }).Name) .AddQuotedArgument("ColumnRef", assocTable.ForeignKeys.Single(fk => { return fk.PrimaryKeyTable.Name != table.Name; }).Name) .AddArgument("Lazy = true"); } }
protected override void CreateAssociationProperties(ClassDeclaration classDeclaration, TableSchema table) { //throw new NotImplementedException(); }
public void CanInheritFromInterface() { ClassDeclaration cdecl = new ClassDeclaration("Fuck").Implements(new InterfaceDeclaration("You")); new CodeBuilder().GenerateCode(Console.Out, "Blah", cdecl); }
/// <summary> /// Creates a plain ol' property representing any column that is not a foreign key or primary key. /// </summary> /// <param name="classDeclaration">The class to which the property is added.</param> /// <param name="column">The column the property represents.</param> protected override void CreateNonKeyProperty(ClassDeclaration classDeclaration, ColumnSchema column) { string propertyName = this.NameProvider.GetPropertyName(column); string fieldName = this.NameProvider.GetFieldName(column); AttributeDeclaration attrib = classDeclaration.AddProperty(propertyName, fieldName, column.DataType, column.Nullable) .AddAttribute("Castle.ActiveRecord.PropertyAttribute") .AddQuotedArgument(column.Name); if (column.SqlType == System.Data.SqlDbType.Image) attrib.AddArgument("ColumnType=\"BinaryBlob\""); if (column.SqlType == System.Data.SqlDbType.Xml) attrib.AddArgument("ColumnType=\"StringClob\""); }
/** * Call back method that must be called as soon as the given <code> * ClassDeclaration</code> object has been traversed. * * @param pClassDeclaration The <code>ClassDeclaration</code> object that * has just been traversed. */ public void actionPerformed( ClassDeclaration pClassDeclaration) { // Nothing to do. }
/** * Call back method that must be called when the given <code> * ClassDeclaration</code> will become the next <i>traverse candidate</i>. * * @param pClassDeclaration The <code>ClassDeclaration</code> object that * will become the next <i>traverse candidate</i>. */ public void performAction( ClassDeclaration pClassDeclaration) { // Nothing to do. }
public void Test() { var @class = new ClassDeclaration("Customer"); new CodeBuilder().GenerateCode(Console.Out, "My.Models", @class); }
public FullClassDeclaration(string FullName, ClassDeclaration ClassDeclaration, NamespaceDeclaration NamespaceDeclaration) { fullName = FullName; classDeclaration = ClassDeclaration; namespaceDeclaration = NamespaceDeclaration; }
/// <summary> /// Add some class attributes. /// </summary> /// <param name="classDecl">The ClassDeclaration instance we're adding an attribute to.</param> /// <param name="table">The database table that the ClassDeclaration represents.</param> protected override void AddClassAttributes(ClassDeclaration classDecl, TableSchema table) { classDecl.AddAttribute("Castle.ActiveRecord.ActiveRecordAttribute").AddQuotedArgument(this.NameProvider.Escape(table.Name)); }