private static void GenerateParameterEntityToString(ParameterEntity entity, StructDeclaration type, PropertyDeclaration valueProperty) { var toString = type.AddMember(new MethodDeclaration("ToString")); toString.Modifiers = Modifiers.Public | Modifiers.Override; toString.ReturnType = typeof(string); if (entity.FinalType == ModelRef.NumberId) { toString.Statements = new ReturnStatement(new MethodInvokeExpression(new MemberReferenceExpression(valueProperty, "ToString"), new MemberReferenceExpression(typeof(CultureInfo), "InvariantCulture"))); } else if (entity.FinalType == ModelRef.String) { toString.Statements = new ReturnStatement(valueProperty); } else { toString.Statements = new ReturnStatement(new MethodInvokeExpression(new MemberReferenceExpression(valueProperty, "ToString"))); } if (entity.FinalType == ModelRef.Object) { toString.ReturnType = toString.ReturnType.MakeNullable(); } }
private StructDeclaration StructDefinitionAst(Brunch <KjuAlphabet> branch) { var nameToken = (Token <KjuAlphabet>)branch.Children[1]; var name = nameToken.Text; var fieldsBranch = (Brunch <KjuAlphabet>)branch.Children[3]; var fieldsNodes = this.StructFieldsAstList(fieldsBranch); var ret = new StructDeclaration(branch.InputRange, name, fieldsNodes); foreach (StructField field in fieldsNodes) { List <KeyValuePair <StructDeclaration, StructField> > candidates; try { candidates = this.fieldsToStructDeclarations[field.Name]; } catch (KeyNotFoundException) { candidates = new List <KeyValuePair <StructDeclaration, StructField> >(); this.fieldsToStructDeclarations.Add(field.Name, candidates); } candidates.Add(new KeyValuePair <StructDeclaration, StructField>(ret, field)); } return(ret); }
public void TestStructWithBuilinTypeName() { var diagnosticsMock = new Moq.Mock <IDiagnostics>(); var diagnostics = diagnosticsMock.Object; var intDecl1 = new StructDeclaration( null, "Int", new List <StructField>() { }); var program = new Program( null, new List <StructDeclaration>() { intDecl1 }, new List <FunctionDeclaration>() { }); Assert.ThrowsException <NameResolverException>(() => this.nameResolver.Run(program, diagnostics)); MockDiagnostics.Verify( diagnosticsMock, NameResolver.TypeIdentifierErrorDiagnosticsType); }
public void TestStructMultipleDeclarations() { var diagnosticsMock = new Moq.Mock <IDiagnostics>(); var diagnostics = diagnosticsMock.Object; var aDecl1 = new StructDeclaration( null, "A", new List <StructField>() { }); var aDecl2 = new StructDeclaration( null, "A", new List <StructField>() { }); var program = new Program( null, new List <StructDeclaration>() { aDecl1, aDecl2 }, new List <FunctionDeclaration>() { }); Assert.ThrowsException <NameResolverException>(() => this.nameResolver.Run(program, diagnostics)); MockDiagnostics.Verify( diagnosticsMock, NameResolver.MultipleDeclarationsDiagnostic, NameResolver.MultipleDeclarationsDiagnostic); }
TypeDeclaration ToStructDeclaration(TypeDefinition definition) { var name = TypeAggregator.ProtocolAttributeName(definition) ?? definition.Name; var moduleName = definition.Namespace; if (TypeAggregator.FilterModuleAndName(platform, moduleName, ref name)) { TypeAggregator.RemapModuleAndName(platform, ref moduleName, ref name, TypeType.Struct); var module = ToModuleDeclaration(moduleName); var structDeclaration = new StructDeclaration { Name = name, Access = ToAccessibility(definition), Module = module, ParentExtension = null, Kind = TypeKind.Struct, Members = new List <Member> (), IsObjC = true, IsFinal = true, IsDeprecated = false, IsUnavailable = false }; return(structDeclaration.MakeUnrooted()); } return(null); }
public void RoundTripStruct() { ModuleDeclaration module = ReflectToModules("public struct Foo {\npublic var x:Int\n } ", "SomeModule").Find(m => m.Name == "SomeModule"); StructDeclaration fooClass = module.AllStructs.Where(cl => cl.Name == "Foo").FirstOrDefault(); Assert.IsNotNull(fooClass); StructDeclaration unrootedFoo = fooClass.MakeUnrooted() as StructDeclaration; Entity entity = new Entity { SharpNamespace = "SomeModule", SharpTypeName = "Foo", Type = unrootedFoo }; TypeDatabase db = new TypeDatabase(); db.Add(entity); MemoryStream ostm = new MemoryStream(); db.Write(ostm, "SomeModule"); ostm.Seek(0, SeekOrigin.Begin); TypeDatabase dbread = new TypeDatabase(); var errors = dbread.Read(ostm); Utils.CheckErrors(errors); Entity entityRead = dbread.EntityForSwiftName("SomeModule.Foo"); Assert.IsNotNull(entityRead); Assert.AreEqual(entity.SharpNamespace, entityRead.SharpNamespace); Assert.AreEqual(entity.SharpTypeName, entityRead.SharpTypeName); Assert.IsTrue(entity.Type is StructDeclaration); }
protected override IEnumerable <object> EnumerateReferences(StructDeclaration record) { yield return(record.AttributeListCollection); yield return(record.BaseList); yield return(record.ConstraintClauseList); yield return(record.ConstructorList); yield return(record.DocumentationCommentList); yield return(record.FieldList); yield return(record.Identifier); yield return(record.MethodList); yield return(record.ModifierList); yield return(record.Namespace); yield return(record.PropertyList); yield return(record.TypeParameterList); yield return(record.UsingDirectiveList); }
public void MutualRecTest2() { var core = new Core(); var def = new StructDeclaration(MetaData.Empty, "A", new List <VariableDeclaration>(new[] { new VariableDeclaration(MetaData.Empty, "var1", type: new UnknownType(MetaData.Empty, "B")), new VariableDeclaration(MetaData.Empty, "var3", type: new UnknownType(MetaData.Empty, "u8")) })); var def2 = new StructDeclaration(MetaData.Empty, "B", new List <VariableDeclaration>(new[] { new VariableDeclaration(MetaData.Empty, "var2", type: new UnknownType(MetaData.Empty, "A")) })); var env = new Environment(Environment.SolarSystem); env.Declarations.Add(def); env.Declarations.Add(def2); core.CheckMutualRec(new[] { def, def2 }); Assert.IsTrue(0 != Errors.ErrList.Count); Errors.PrintErrorInfo(); }
public void TestStructSameFieldName() { var diagnosticsMock = new Moq.Mock <IDiagnostics>(); var diagnostics = diagnosticsMock.Object; var declA = new StructDeclaration( null, "A", new List <StructField>() { new StructField(null, "x", IntType.Instance), new StructField(null, "x", BoolType.Instance), }); var program = new Program( null, new List <StructDeclaration>() { declA }, new List <FunctionDeclaration>() { }); Assert.ThrowsException <NameResolverException>(() => this.nameResolver.Run(program, diagnostics)); MockDiagnostics.Verify( diagnosticsMock, NameResolver.MultipleDeclarationsDiagnostic); }
public void TestUnused() { /* * def kju() : Unit { * struct X {}; * } */ var dummyRange = new Core.Lexer.Range(new StringLocation(0), new StringLocation(0)); var xDeclaration = new StructDeclaration(dummyRange, "X", new List <StructField>()); var xType = StructType.GetInstance(xDeclaration); var kjuInstructions = new List <Expression> { xDeclaration }; var kjuDeclaration = new FunctionDeclaration( dummyRange, "kju", new ArrayType(UnitType.Instance), new List <VariableDeclaration>(), new InstructionBlock(dummyRange, kjuInstructions), false); var root = new Program(dummyRange, new List <StructDeclaration>(), new List <FunctionDeclaration> { kjuDeclaration }); this.CheckAnswer(root, new HashSet <DataType>() { xType }); }
public SecondaryType( MetaData metaData, [NotNull] string name, [CanBeNull] StructDeclaration @struct = null) : base(metaData, name, 4) { Struct = @struct; }
public DeclaredKontrolStructConstructor(DeclaredKontrolModule module, IBlockContext methodContext, StructDeclaration to2Struct) { this.module = module; Parameters = to2Struct.constructorParameters.Select(p => new RealizedParameter(methodContext, p)).ToList(); ReturnType = to2Struct.typeDelegate.UnderlyingType(methodContext.ModuleContext); this.methodContext = methodContext; this.to2Struct = to2Struct; }
public static StructType GetInstance(StructDeclaration structDeclaration) { if (structDeclaration.StructType == null) { structDeclaration.StructType = new StructType(structDeclaration.Name, structDeclaration.Fields); } return(structDeclaration.StructType); }
public void TestStructFunctionParameters() { var aDecl = new StructDeclaration( null, "A", new List <StructField>()); var aParam = new VariableDeclaration( null, new UnresolvedType("A", null), "a", null); var f = new FunctionDeclaration( null, "f", new UnresolvedType("A", null), new List <VariableDeclaration>() { aParam }, new InstructionBlock( null, new List <Expression>() { new FunctionCall( null, "f", new List <Expression>() { aParam }), new ReturnStatement( null, new Variable( null, "a")), }), false); var program = new Program( null, new List <StructDeclaration>() { aDecl }, new List <FunctionDeclaration>() { f }); this.nameResolver.Run(program, null); Assert.AreEqual(StructType.GetInstance(aDecl), f.ReturnType); Assert.AreEqual(StructType.GetInstance(aDecl), aParam.VariableType); }
/// <summary> /// Gets whether <paramref name="type"/> matches the specified struct declaration or contains it recursively (as an array item type or as a inner field). /// </summary> public static bool IsOrContainsStruct(IType type, StructDeclaration structDecl) { if (type is StructType structTy) { return(structTy.Declaration == structDecl || structTy.Declaration.Fields.Any(f => IsOrContainsStruct(f.Type, structDecl))); } else if (type is ArrayType arrayTy) { return(IsOrContainsStruct(arrayTy.ItemType, structDecl)); } return(false); }
private static void GenerateParameterEntityEqualTypedMethod(StructDeclaration type, PropertyDeclaration valueProperty) { var equal = type.AddMember(new MethodDeclaration(nameof(object.Equals))); equal.Modifiers = Modifiers.Public; equal.ReturnType = typeof(bool); var objArg = equal.AddArgument("other", new TypeReference(type)); Expression returnExpression = new MethodInvokeExpression( new MemberReferenceExpression(typeof(object), "Equals"), valueProperty, new MemberReferenceExpression(objArg, valueProperty)); equal.Statements = new ReturnStatement(returnExpression); }
public override void SurroundWith(Environment environment) { base.SurroundWith(environment); if (null == Struct) { Struct = Env.FindDeclarationByName(Name) as StructDeclaration; } if (null != Struct) { Struct.Used = true; return; } Errors.Add($"{MetaData.GetErrorHeader()}cannot resolve type {Name}"); throw new CompilerException(); }
public override void SurroundWith(Environment environment) { base.SurroundWith(environment); if (null == Struct) { Struct = Env.FindDeclarationByName(Name) as StructDeclaration; } if (null == Struct) { Errors.AddAndThrow($"{MetaData.GetErrorHeader()}cannot resolve type {Name}"); } else { Struct.UsageCount++; } }
private static void GenerateParameterEntityGetHashCode(StructDeclaration type, PropertyDeclaration valueProperty) { var equal = type.AddMember(new MethodDeclaration(nameof(object.GetHashCode))); equal.Modifiers = Modifiers.Public | Modifiers.Override; equal.ReturnType = typeof(int); var statements = new StatementCollection { new ReturnStatement( new MethodInvokeExpression( new MemberReferenceExpression(new TypeReferenceExpression(typeof(HashCode)), nameof(HashCode.Combine)), valueProperty)), }; equal.Statements = statements; }
public void TestStruct() { var x = new VariableDeclaration( null, new UnresolvedType("A", null), "x", null); var kju = new FunctionDeclaration( null, "kju", UnitType.Instance, new List <VariableDeclaration>() { }, new InstructionBlock( null, new List <Expression>() { x, }), false); var globalADecl = new StructDeclaration( null, "A", new List <StructField>() { new StructField(null, "a", new UnresolvedType("A", null)) }); var program = new Program( null, new List <StructDeclaration>() { globalADecl }, new List <FunctionDeclaration>() { kju }); this.nameResolver.Run(program, null); Assert.AreEqual(StructType.GetInstance(globalADecl), x.VariableType); Assert.AreEqual(StructType.GetInstance(globalADecl), globalADecl.Fields[0].Type); }
private static void GenerateParameterEntityEqualMethod(StructDeclaration type) { var equal = type.AddMember(new MethodDeclaration(nameof(object.Equals))); equal.Modifiers = Modifiers.Public | Modifiers.Override; equal.ReturnType = typeof(bool); var objArg = equal.AddArgument("obj", new TypeReference(typeof(object)).MakeNullable()); equal.Statements = new StatementCollection() { new ConditionStatement { Condition = new IsInstanceOfTypeExpression(objArg, type), TrueStatements = new ReturnStatement(new ThisExpression().CreateInvokeMethodExpression("Equals", new CastExpression(objArg, type))), FalseStatements = new ReturnStatement(LiteralExpression.False()), }, }; }
protected override async Task <StructDeclaration> AssignUpsertedReferences(StructDeclaration 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.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); }
public void TestStructLayout() { ModuleDeclaration module = ReflectToModules("public struct Foo { public var X:Int;\n public var Y:Bool; public var Z: Float; }", "SomeModule") .Find(m => m.Name == "SomeModule"); Assert.NotNull(module); StructDeclaration theStruct = module.Structs.FirstOrDefault(s => s.Name == "Foo"); Assert.NotNull(theStruct); List <PropertyDeclaration> props = theStruct.Members.OfType <PropertyDeclaration> ().ToList(); Assert.AreEqual(3, props.Count); Assert.AreEqual("X", props [0].Name); Assert.AreEqual("Y", props [1].Name); Assert.AreEqual("Z", props [2].Name); Assert.AreEqual("Swift.Int", props [0].TypeName); Assert.AreEqual("Swift.Bool", props [1].TypeName); Assert.AreEqual("Swift.Float", props [2].TypeName); }
private static void GenerateParameterEntityEqualityOperators(StructDeclaration type) { var equal = type.AddMember(new OperatorDeclaration("==")); equal.Modifiers = Modifiers.Public | Modifiers.Static; equal.ReturnType = typeof(bool); equal.Arguments.Add(new MethodArgumentDeclaration(new TypeReference(type), "a")); equal.Arguments.Add(new MethodArgumentDeclaration(new TypeReference(type), "b")); equal.Statements.Add(new ReturnStatement(new TypeReferenceExpression(new TypeReference(typeof(EqualityComparer <>)).MakeGeneric(type)).CreateMemberReferenceExpression("Default").CreateInvokeMethodExpression("Equals", new ArgumentReferenceExpression("a"), new ArgumentReferenceExpression("b")))); var notEqual = type.AddMember(new OperatorDeclaration("!=")); notEqual.Modifiers = Modifiers.Public | Modifiers.Static; notEqual.ReturnType = typeof(bool); notEqual.Arguments.Add(new MethodArgumentDeclaration(new TypeReference(type), "a")); notEqual.Arguments.Add(new MethodArgumentDeclaration(new TypeReference(type), "b")); notEqual.Statements.Add(new ReturnStatement(new UnaryExpression(UnaryOperator.Not, new BinaryExpression(BinaryOperator.Equals, new ArgumentReferenceExpression("a"), new ArgumentReferenceExpression("b"))))); }
public void TestStructAlloc() { var aDecl = new StructDeclaration( null, "A", new List <StructField>()); var aAlloc = new StructAlloc( null, new UnresolvedType("A", null)); var kju = new FunctionDeclaration( null, "kju", UnitType.Instance, new List <VariableDeclaration>(), new InstructionBlock( null, new List <Expression>() { aAlloc }), false); var program = new Program( null, new List <StructDeclaration>() { aDecl }, new List <FunctionDeclaration>() { kju }); this.nameResolver.Run(program, null); Assert.AreEqual(StructType.GetInstance(aDecl), aAlloc.AllocType); }
public override void VisitStructObject(StructObjectDeclaration element) { //throw new NotImplementedException(); //s s1; if (element != null) { if (mVariableMap.ContainsKey(element.getStructName().getText())) { Object name = mVariableMap[element.getStructName().getText()]; if (GetTypeOfElement((Element)(name)) == 4) { StructDeclaration temp = (StructDeclaration)name; if (temp != null) { StructDeclaration obj = new StructDeclaration(); List<ScalarVariableDeclaration> l1 = new List<ScalarVariableDeclaration>(); l1 = temp.getVarType(); for (int i = 0; i < l1.Count; i++) obj.setVarType(l1[i]); obj.setName(element.getObjName()); mVariableMap.Add(element.getObjName().getText(), obj); } else { Console.Write("Variable name used\n"); sendres(112, "Variable name used\n"); } } else Console.Write("Object not of type struct\n"); } else sendres(112, "Structure not found\n"); } else Console.Write("Null struct object\n"); }
protected override Expression <Func <StructDeclaration, bool> > FindExisting(StructDeclaration record) => existing => existing.IdentifierId == record.IdentifierId && existing.NamespaceId == record.NamespaceId;
private void DefineType(string packageName, AccelTypeInfo declaringType, TypeBuilder declaringTypeBuilder, StructDeclaration def, Dictionary <string, AccelTypeInfo> result) { string name = def.Name; string fullName = def.IsNested ? $"{declaringType.FullName}+{def.Name}" : $"{packageName}.{def.Name}"; Dictionary <string, AccelFieldInfo> fields = new Dictionary <string, AccelFieldInfo>(def.Declarations.Declarations.Length); Type baseType = def.IsRef ? typeof(object) : typeof(ValueType); TypeBuilder builder = RuntimeInjector.DefinePublicType(def.IsNested ? name : fullName, def.IsFinal, declaringTypeBuilder, baseType, Type.EmptyTypes); AccelTypeInfo info = new AccelTypeInfo(name, fullName, def.Doc, TypeVisibility.Public, def.IsFinal, def.IsRef, def.IsNested, def.IsFieldIndexContinuous, (int)def.Size, declaringType, fields); for (int i = 0; i < def.Declarations.Declarations.Length; i++) { IDeclaration declaration = def.Declarations.Declarations[i]; switch (declaration) { case FieldDeclaration fieldDeclaration: Type fieldType = GetType(fieldDeclaration.Type); Type realType = fieldDeclaration.RealType == null ? null : GetType(fieldDeclaration.RealType); builder.DefineField(fieldDeclaration.Name, fieldType, FieldAttributes.Public); AccelFieldInfo fieldInfo = new AccelFieldInfo(fieldDeclaration.Name, fieldDeclaration.Doc, (int)fieldDeclaration.Index, fieldDeclaration.IsObsolete, fieldDeclaration.IsNeverNull, info, fieldType, realType); fields.Add(fieldDeclaration.Name, fieldInfo); break; case StructDeclaration structDeclaration: DefineType(packageName, info, builder, structDeclaration, result); break; default: continue; } } Type type = builder.CreateType(); info.TypeHandle = type.TypeHandle; foreach (FieldInfo field in type.GetFields()) { fields[field.Name].FieldHandle = field.FieldHandle; } result.Add(fullName, info); }
public virtual TReturn Visit(StructDeclaration node, TParam param) => throw new NotImplementedException();
public virtual TReturn Visit(StructDeclaration node, TParam param) { node.Fields.ForEach(f => f.Accept(this, param)); return(DefaultReturn); }
public override void VisitStructDeclaration(StructDeclaration element) { Console.Write("Struct "); VisitElement(element.getName()); Console.Write(";\n"); }
public int Visit(StructDeclaration declaration) { throw new NotImplementedException(); }
public abstract void VisitStructDeclaration(StructDeclaration element);
public override void VisitStructDeclaration(StructDeclaration element) { //throw new NotImplementedException(); //struct s{int a;}; if (element != null) { if (mVariableMap.ContainsKey(element.getName().getText())) { sendres(112, "Variable declared\n"); Console.Write("Variable declared\n"); } else mVariableMap.Add(element.getName().getText(), element); } else Console.Write("Null Structure element\n"); }
public static Int32 Parse(List<Token> src, Int32 begin, out StructDeclaration decln) { return Parser.ParseSequence( src, begin, out decln, // specifier_qualifier_list _specifier_qualifier_list.Parse, // struct_declarator_list _struct_declarator_list.Parse, // ';' Parser.GetOperatorParser(OperatorVal.SEMICOLON), (DeclnSpecs specs, List<Declr> declrs, Boolean _) => new StructDeclaration(specs, declrs) ); }
public override void VisitStructDeclaration(StructDeclaration element) { //throw new NotImplementedException(); }