Add() public method

public Add ( Declaration, d ) : void
d Declaration,
return void
        private void CreateMemebers()
        {
            var namedTypeSymbol = (INamedTypeSymbol)Type;

            var methodTableType = new NamedTypeImpl()
            {
                Name = TypeName, TypeKind = TypeKind.Unknown, ContainingType = (INamedTypeSymbol)Type
            };

            if (!Type.IsAbstract && (Type.TypeKind == TypeKind.Class || Type.TypeKind == TypeKind.Struct))
            {
                Declarations.Add(new CCodeNewDeclaration(namedTypeSymbol));
            }

            Declarations.Add(new CCodeGetTypeDeclaration(namedTypeSymbol));

            if (Type.IsValueType && Type.SpecialType != SpecialType.System_Void)
            {
                Declarations.Add(new CCodeBoxRefDeclaration(namedTypeSymbol));
                Declarations.Add(new CCodeUnboxToDeclaration(namedTypeSymbol));
            }

            // transition to external definitions
            foreach (var declaration in Declarations.OfType <CCodeMethodDeclaration>().Where(m => m.MethodBodyOpt != null))
            {
                declaration.ToDefinition(Definitions, methodTableType);
            }
        }
        /// <summary>
        /// The object factory for a particular data collection instance.
        /// </summary>
        public virtual void CreateObjectsFromData(Declarations declarations, System.Data.DataSet data)
        {
            // Do nothing if we have nothing
            if (data == null || data.Tables.Count == 0 || data.Tables[0].Rows.Count == 0)
            {
                return;
            }


            // Create a local variable for the new instance.
            Declaration newobj = null;

            // Create a local variable for the data row instance.
            System.Data.DataRow dr = null;


            // Iterate through the table rows
            for (int i = 0; i < data.Tables[0].Rows.Count; i++)
            {
                // Get a reference to the data row
                dr = data.Tables[0].Rows[i];
                // Create a new object instance
                newobj = System.Activator.CreateInstance(declarations.ContainsType[0]) as Declaration;
                // Let the instance set its own members
                newobj.SetMembers(ref dr);
                // Add the new object to the collection instance
                declarations.Add(newobj);
            }
        }
        /// <summary>Common method for adding declaration with some default values</summary>
        private void AddDeclarationItem(IMock <ParserRuleContext> context,
                                        Selection selection,
                                        QualifiedMemberName?qualifiedName = null,
                                        DeclarationType declarationType   = DeclarationType.Project,
                                        string identifierName             = "identifierName")
        {
            Declaration declarationItem = null;
            var         qualName        = qualifiedName ?? new QualifiedMemberName(_module, "fakeModule");

            declarationItem = new Declaration(
                qualifiedName: qualName,
                parentScope: "module.proc",
                asTypeName: "asTypeName",
                isSelfAssigned: false,
                isWithEvents: false,
                accessibility: Accessibility.Public,
                declarationType: declarationType,
                context: context.Object,
                selection: selection
                );

            _declarations.Add(declarationItem);
            if (_listDeclarations == null)
            {
                _listDeclarations = new List <Declaration>();
            }
            _listDeclarations.Add(declarationItem);
        }
        /// <summary>
        /// Ajoute des déclarations à ce Container à partir d'un block Access.
        /// </summary>
        /// <param name="block"></param>
        void AddDeclarationsFromAccessBlock(Language.NamedBlockDeclaration block, Semantic.TypeTable table)
        {
            foreach (Language.Instruction instruction in block.Instructions)
            {
                if (instruction is Language.FunctionDeclaration)
                {
                    // Vérifie que le type de retour de la fonction est public.
                    Language.FunctionDeclaration decl = (Language.FunctionDeclaration)instruction;
                    decl.Func.Owner = table.Types[Language.SemanticConstants.StateClass];
                    if (!decl.Func.IsPublic)
                    {
                        ParsingLog.AddWarning("Les fonctions contenues dans le block access doivent être publiques.",
                                              instruction.Line, instruction.Character, instruction.Source);
                    }
                    if (decl.Func.ReturnType.IsPrivateOrHasPrivateGenericArgs())
                    {
                        ParsingLog.AddWarning("Les types de retour des déclaration de fonction du bloc access doivent être des types publics" +
                                              " et ne pas contenir de paramètre générique privé. (donné : "
                                              + decl.Func.ReturnType.GetFullName() + ")",
                                              instruction.Line, instruction.Character, instruction.Source);
                    }

                    // Vérification du return type.
                    List <string> outReasons;
                    if (!decl.Func.ReturnType.DoesSupportSerialization(out outReasons))
                    {
                        string error;
                        error = "Le type de retour de la fonction '" + decl.Func.GetFullName() + "' (" + decl.Func.ReturnType.GetFullName() +
                                ") ne prend pas en charge la sérialisation. Raisons : ";
                        error += Tools.StringUtils.Join(outReasons, ", ") + ".";
                        ParsingLog.AddWarning(error, decl.Line, decl.Character, decl.Source);
                    }

                    // Vérification des types des arguments.
                    foreach (Language.FunctionArgument arg in decl.Func.Arguments)
                    {
                        if (!arg.ArgType.DoesSupportSerialization(out outReasons))
                        {
                            string error;
                            error = "Le type de l'argument '" + arg.ArgName + "' (" + arg.ArgType + ") de la fonction " + decl.Func.GetFullName() +
                                    " ne prend pas en charge la sérialisation. Reasons : ";


                            error += Tools.StringUtils.Join(outReasons, ", ") + ".";
                            ParsingLog.AddWarning(error, decl.Line, decl.Character, decl.Source);
                        }
                    }
                    Declarations.Add((Language.FunctionDeclaration)instruction);
                }
                else
                {
                    ParsingLog.AddError("Instruction de type " + instruction.GetType().Name + " invalide dans un AccessBlock",
                                        instruction.Line,
                                        instruction.Character,
                                        instruction.Source
                                        );
                }
            }
        }
示例#5
0
 public ImportUri(string uri)
 {
     _uri = uri;
     Declarations.Add(new Declaration {
         Property = "@import", Value = uri
     });
     Selector = _hash.GetHashCode(this, null);
 }
示例#6
0
 /// <summary>
 /// スニペット変数を追加する
 /// </summary>
 /// <param name="literal">変数</param>
 public void AddDeclaration(Literal literal)
 {
     if (Declarations is null)
     {
         Declarations = new List <Literal>();
     }
     Declarations.Add(literal);
 }
示例#7
0
 /// <summary>
 /// スニペット変数を追加する
 /// </summary>
 /// <param name="id">変数名</param>
 /// <param name="toolTip">説明</param>
 /// <param name="_default">デフォルト値</param>
 /// <param name="function">適用する関数</param>
 /// <param name="functionValue">関数に使用する引数</param>
 public void AddDeclaration(string id, string toolTip, string _default, Function?function, string functionValue)
 {
     if (Declarations is null)
     {
         Declarations = new List <Literal>();
     }
     Declarations.Add(new Literal(id, function, functionValue));
 }
示例#8
0
 /// <summary>
 /// スニペット変数を追加する
 /// </summary>
 /// <param name="id">変数名</param>
 /// <param name="toolTip">説明</param>
 /// <param name="_default">デフォルト値</param>
 public void AddDeclaration(string id, string toolTip, string _default)
 {
     if (Declarations is null)
     {
         Declarations = new List <Literal>();
     }
     Declarations.Add(new Literal(id, toolTip, _default));
 }
示例#9
0
 public void Apply()
 {
     Declarations.Add(AddDeclaration());
     ISupportInitializeBegin.Add(AddISupportInitializeBegin());
     PropsSetup.Add(AddPropsSetup());
     ISupportInitializeEnd.Add(AddISupportInitializeEnd());
     Instantiations.Add(AddInstantiation());
 }
        public override void VisitEnumDeclaration(EnumDeclarationSyntax node)
        {
            var c = node.Identifier.Text;

            if (!Skip.Contains(c))
            {
                Declarations.Add(c);
            }
            base.VisitEnumDeclaration(node);
        }
示例#11
0
 private void CreateMemebers()
 {
     Declarations.Add(new CCodeFieldDeclaration(new FieldImpl {
         Name = "_class", Type = Type
     }));
     foreach (var interfaceMethod in [email protected]().OfType <IMethodSymbol>().Union([email protected]()))
     {
         Declarations.Add(new CCodeMethodDeclaration(Type, this.CreateWrapperMethod(interfaceMethod)));
     }
 }
 private void CreateMemebers()
 {
     Declarations.Add(new CCodeFieldDeclaration(new FieldImpl {
         Name = "_class", Type = Type
     }));
     foreach (var method in [email protected]().OfType <IMethodSymbol>().Union([email protected](i => i.GetMembers().OfType <IMethodSymbol>())))
     {
         Declarations.Add(new CCodeMethodDeclaration(this.CreateWrapperMethod(method)));
     }
 }
示例#13
0
 public VBProjectParseResult(IEnumerable <VBComponentParseResult> parseResults)
 {
     _parseResults = parseResults;
     _declarations = new Declarations();
     foreach (var declaration in VbaStandardLib.Declarations)
     {
         _declarations.Add(declaration);
     }
     IdentifySymbols();
     IdentifySymbolUsages();
 }
示例#14
0
        private void CreateMemebers()
        {
            var namedTypeSymbol = (INamedTypeSymbol)Type;

            Declarations.Add(new CCodeGetTypeDeclaration(namedTypeSymbol));

            if (Type.IsValueType && Type.SpecialType != SpecialType.System_Void)
            {
                Declarations.Add(new CCodeBoxRefDeclaration(namedTypeSymbol));
                Declarations.Add(new CCodeUnboxToDeclaration(namedTypeSymbol));
            }
        }
示例#15
0
文件: parse.cs 项目: cwensley/monomac
    void ProcessInterface(string iface)
    {
        bool   need_close = iface.IndexOf("{") != -1;
        var    cols       = iface.Split();
        string line;

        //Console.WriteLine ("**** {0} ", iface);
        types.Add(cols [1]);
        if (extraAttribute != null)
        {
            gencs.Write("\n\t[{0}]", extraAttribute);
        }
        if (cols.Length >= 4)
        {
            gencs.WriteLine("\n\t[BaseType (typeof ({0}))]", cols [3]);
        }
        gencs.WriteLine("\t{0}interface {1} {{", limit == null ? "" : "public partial ", cols [1]);

        //while ((line = r.ReadLine ()) != null && (need_close && !line.StartsWith ("}"))){
        //	if (line == "{")
        //		need_close = true;
        //}
        line = r.ReadLine();
        if (line == "{")
        {
            need_close = true;
        }
        while (line != null && (need_close && line != "}"))
        {
            line = r.ReadLine();
        }

        var decl = new Declarations(gencs);

        while ((line = r.ReadLine()) != null && !line.StartsWith("@end"))
        {
            string full = "";

            while ((line = r.ReadLine()) != null && !line.StartsWith("@end"))
            {
                full += line;
                if (full.IndexOf(';') != -1)
                {
                    full = full.Replace('\n', ' ');
                    decl.Add(ProcessDeclaration(false, full, false));
                    full = "";
                }
            }
            break;
        }
        decl.Generate(extraAttribute);
        gencs.WriteLine("\t}");
    }
示例#16
0
        public VBProjectParseResult(VBProject project, IEnumerable <VBComponentParseResult> parseResults)
        {
            _project      = project;
            _parseResults = parseResults;
            _declarations = new Declarations();

            var projectIdentifier  = project.Name;
            var memberName         = new QualifiedMemberName(new QualifiedModuleName(project), projectIdentifier);
            var projectDeclaration = new Declaration(memberName, "VBE", projectIdentifier, false, false, Accessibility.Global, DeclarationType.Project, false);

            _declarations.Add(projectDeclaration);

            foreach (var declaration in VbaStandardLib.Declarations)
            {
                _declarations.Add(declaration);
            }

            foreach (var declaration in _parseResults.SelectMany(item => item.Declarations))
            {
                _declarations.Add(declaration);
            }
        }
        private void CreateMemebers()
        {
            var namedTypeSymbol = (INamedTypeSymbol)Type;

            Declarations.Add(new CCodeFieldDeclaration(new FieldImpl {
                Name = "_class", Type = Type
            }));
            Declarations.Add(new CCodeObjectCastOperatorDeclaration(namedTypeSymbol, GetReceiver(namedTypeSymbol, this.@interface)));
            foreach (var interfaceMethod in [email protected]().OfType <IMethodSymbol>().Union([email protected]()))
            {
                Declarations.Add(new CCodeMethodDeclaration(Type, this.CreateWrapperMethod(interfaceMethod)));
            }
        }
示例#18
0
        public void AddDeclaration(IDeclaration declaration)
        {
            List <IDeclaration> declarations;

            if (declaration.Name != null)
            {
                string name = declaration.Name.Text;
                if (string.IsNullOrEmpty(name))
                {
                    return;
                }

                if (!Declarations.TryGetValue(name, out declarations))
                {
                    declarations = new List <IDeclaration>();
                    Declarations.Add(name, declarations);
                }
            }
            else
            {
                declarations = new List <IDeclaration>();
            }

            var genericsDeclarator = declaration as IGenerics;

            if (genericsDeclarator != null)
            {
                for (int i = 0; i < genericsDeclarator.GenericParameters.Count; i++)
                {
                    var genericArgument = genericsDeclarator.GenericParameters[i];
                    var genericName     = genericArgument.Name.Text;
                    List <GenericDeclaration> generics;
                    if (!Generics.TryGetValue(genericName, out generics))
                    {
                        generics = new List <GenericDeclaration>();
                        Generics.Add(genericName, generics);
                    }

                    generics.Add(new GenericDeclaration(genericArgument.Name, genericsDeclarator, i, false)
                    {
                        Span = genericArgument.Span
                    });
                }
            }

            if (!declarations.Contains(declaration))
            {
                declarations.Add(declaration);
            }
        }
示例#19
0
        public void Add(FBXDeclarationNode node)
        {
            List <FBXDeclarationNode> list;

            if (!Declarations.TryGetValue(node.Type, out list))
            {
                list = new List <FBXDeclarationNode> {
                    node
                };
                Declarations.Add(node.Type, list);
            }
            else
            {
                list.Add(node);
            }
        }
示例#20
0
        private void CreateMemebers()
        {
            var namedTypeSymbol = (INamedTypeSymbol)Type;

            if (!Type.IsAbstract && (Type.TypeKind == TypeKind.Class || Type.TypeKind == TypeKind.Struct))
            {
                Declarations.Add(new CCodeNewDeclaration(namedTypeSymbol));
            }

            Declarations.Add(new CCodeGetTypeDeclaration(namedTypeSymbol));

            if (Type.IsValueType && Type.SpecialType != SpecialType.System_Void)
            {
                Declarations.Add(new CCodeBoxRefDeclaration(namedTypeSymbol));
                Declarations.Add(new CCodeUnboxToDeclaration(namedTypeSymbol));
            }
        }
        /// <summary>
        /// The object factory for a particular data collection instance.
        /// </summary>
        public virtual void CreateObjectsFromData(Declarations declarations, System.Data.SqlClient.SqlDataReader data)
        {
            // Do nothing if we have nothing
            if (data == null) return;

            // Create a local variable for the new instance.
            Declaration newobj = null;
            // Iterate through the data reader
            while (data.Read())
            {
                // Create a new object instance
                newobj = System.Activator.CreateInstance(declarations.ContainsType[0]) as Declaration;
                // Let the instance set its own members
                newobj.SetMembers(ref data);
                // Add the new object to the collection instance
                declarations.Add(newobj);
            }
        }
示例#22
0
    void ProcessProtocol(string proto)
    {
        string [] d = proto.Split(new char [] { ' ', '<', '>' });
        string    line;

        types.Add(d [1]);
        if (extraAttribute != null)
        {
            gencs.WriteLine("\n\t[{0}]", extraAttribute);
        }
        gencs.WriteLine("\n\t[BaseType (typeof ({0}))]", d.Length > 2 ? d [2] : "NSObject");
        gencs.WriteLine("\t[Model]");
        gencs.WriteLine("\tinterface {0} {{", d [1]);
        bool optional = false;

        var decl = new Declarations(gencs);

        while ((line = r.ReadLine()) != null && !line.StartsWith("@end"))
        {
            if (line.StartsWith("@optional"))
            {
                optional = true;
            }

            string full = "";
            while ((line = r.ReadLine()) != null && !line.StartsWith("@end"))
            {
                full += line;
                if (full.IndexOf(';') != -1)
                {
                    full = full.Replace('\n', ' ');
                    decl.Add(ProcessDeclaration(true, full, optional));
                    full = "";
                }
            }
            if (line.StartsWith("@end"))
            {
                break;
            }
        }
        decl.Generate(extraAttribute);
        gencs.WriteLine("\t}");
    }
示例#23
0
        public override IMetaEntityExpressionTarget SelectTarget(string expressionPathNode)
        {
            if (MetaEntityTools.IsMultinodeExpressionPath(expressionPathNode))
            {
                return(Parent.SelectTargetByPath(expressionPathNode));
            }

            var head = Declarations.FirstOrDefault(x => x.name.Equals(expressionPathNode));

            if (head == null)
            {
                MetaEntityClass item = new MetaEntityClass();
                item.name   = expressionPathNode;
                item.Parent = this;

                Declarations.Add(item);
                head = item;
            }


            return(head);
        }
        /// <summary>
        /// The object factory for a particular data collection instance.
        /// </summary>
        public virtual void CreateObjectsFromData(Declarations declarations, System.Data.SqlClient.SqlDataReader data)
        {
            // Do nothing if we have nothing
            if (data == null)
            {
                return;
            }


            // Create a local variable for the new instance.
            Declaration newobj = null;

            // Iterate through the data reader
            while (data.Read())
            {
                // Create a new object instance
                newobj = System.Activator.CreateInstance(declarations.ContainsType[0]) as Declaration;
                // Let the instance set its own members
                newobj.SetMembers(ref data);
                // Add the new object to the collection instance
                declarations.Add(newobj);
            }
        }
示例#25
0
文件: Block.cs 项目: arlm/CLanguage
 public void AddFunction(FunctionDeclaration dec)
 {
     Declarations.Add(dec);
     Functions.Add(dec);
 }
示例#26
0
文件: Block.cs 项目: arlm/CLanguage
 public void AddVariable(VariableDeclaration dec)
 {
     Declarations.Add(dec);
     Variables.Add(dec);
 }
示例#27
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="node">対象Node</param>
        /// <param name="semanticModel">対象ソースのsemanticModel</param>
        /// <param name="parent">親IAnalyzeItem</param>
        /// <param name="container">イベントコンテナ</param>
        public ItemFor(ForStatementSyntax node, SemanticModel semanticModel, IAnalyzeItem parent, EventContainer container) : base(parent, node, semanticModel, container)
        {
            ItemType = ItemTypes.MethodStatement;

            // 宣言部
            if (node.Declaration != null)
            {
                // 型設定
                IsVar = node.Declaration.Type.IsVar;
                var declaredSymbol = semanticModel.GetDeclaredSymbol(node.Declaration.Variables.First());
                var parts          = ((ILocalSymbol)declaredSymbol).Type.ToDisplayParts(SymbolDisplayFormat.MinimallyQualifiedFormat);
                foreach (var part in parts)
                {
                    // スペースの場合は型設定に含めない
                    if (part.Kind == SymbolDisplayPartKind.Space)
                    {
                        continue;
                    }

                    var name = Expression.GetSymbolName(part, true);
                    var type = Expression.GetSymbolTypeName(part.Symbol);
                    if (part.Kind == SymbolDisplayPartKind.ClassName)
                    {
                        // 外部ファイル参照イベント発行
                        RaiseOtherFileReferenced(node, part.Symbol);
                    }

                    Types.Add(new Expression(name, type));
                }

                // ローカル定義
                foreach (var variable in node.Declaration.Variables)
                {
                    var declaration = semanticModel.GetOperation(variable);
                    Declarations.Add(OperationFactory.GetExpressionList(declaration, container));
                }
            }
            else if (node.Initializers != null)
            {
                // 既存定義
                foreach (var initializer in node.Initializers)
                {
                    var declaration = semanticModel.GetOperation(initializer);
                    Declarations.Add(OperationFactory.GetExpressionList(declaration, container));
                }
            }

            // 計算部
            foreach (var increment in node.Incrementors)
            {
                var incrementOperator = semanticModel.GetOperation(increment);
                Incrementors.Add(OperationFactory.GetExpressionList(incrementOperator, container));
            }

            // 条件部
            var condition = semanticModel.GetOperation(node.Condition);

            Conditions.AddRange(OperationFactory.GetExpressionList(condition, container));

            // 内部処理設定
            var block = node.Statement as BlockSyntax;

            foreach (var statement in block.Statements)
            {
                Members.Add(ItemFactory.Create(statement, semanticModel, container, this));
            }
        }
示例#28
0
        /// <summary>
        /// Adds a vertex declation to the buffer
        /// </summary>
        /// <param name="name">Specifies the name of the generic vertex attribute to be modified.</param>
        /// <param name="size">Specifies the number of components per generic vertex attribute.</param>
        public void AddDeclaration(string name, int size)
        {
            Declarations.Add(new VertexDeclaration(name, size));

            Stride += size;
        }
示例#29
0
        public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
        {
            if (context.Node is ClassDeclarationSyntax cls)
            {
                ISymbol currentType = ModelExtensions.GetDeclaredSymbol(context.SemanticModel, cls);
                if (HasNamedAttribute(
                        currentType,
                        "Microsoft.DotNet.Internal.Testing.DependencyInjection.Abstractions.TestDependencyInjectionSetupAttribute"
                        ))
                {
                    bool error  = false;
                    var  nested = cls.Parent as ClassDeclarationSyntax;
                    if (nested == null)
                    {
                        Diagnostics.Add(Error(DiagnosticIds.NestedClassRequired, $"Class {cls.Identifier.Text} must be nested inside class to use [TestDependencyInjectionSetupAttribute]", cls));
                        error = true;
                    }

                    if (cls.Modifiers.All(m => m.Kind() != SyntaxKind.StaticKeyword))
                    {
                        Diagnostics.Add(Error(DiagnosticIds.StaticClassRequired, $"Class {cls.Identifier.Text} must be declared static to use [TestDependencyInjectionSetupAttribute]", nested));
                        error = true;
                    }

                    if (!HasDependencyInjectionReference(context))
                    {
                        Diagnostics.Add(
                            Error(
                                DiagnosticIds.DependencyInjectionRequired,
                                "Missing reference to Microsoft.Extensions.DependencyInjection to use [TestDependencyInjectionSetupAttribute]",
                                cls
                                )
                            );
                        error = true;
                    }

                    if (error)
                    {
                        return;
                    }

                    if (nested.Modifiers.All(m => m.Kind() != SyntaxKind.PartialKeyword))
                    {
                        Diagnostics.Add(Error(DiagnosticIds.PartialClassRequired, $"Class {nested.Identifier.Text} must be declared partial to use [TestDependencyInjectionSetupAttribute]", nested));
                        error = true;
                    }

                    if (!(nested.Parent is NamespaceDeclarationSyntax))
                    {
                        Diagnostics.Add(Error(DiagnosticIds.NamespaceRequired, $"Class {nested.Identifier.Text} must be inside a namespace to use [TestDependencyInjectionSetupAttribute]", nested));
                        error = true;
                    }

                    if (error)
                    {
                        return;
                    }

                    ISymbol parentType = ModelExtensions.GetDeclaredSymbol(context.SemanticModel, nested);
                    Declarations.Add(
                        new TestConfigDeclaration(
                            parentType.ContainingNamespace.FullName(),
                            nested.Identifier.Text,
                            currentType,
                            cls
                            )
                        );
                }
            }

            if (context.Node is MethodDeclarationSyntax method)
            {
                var sMethod = ModelExtensions.GetDeclaredSymbol(context.SemanticModel, method) as IMethodSymbol;
                TestConfigDeclaration decl = Declarations.FirstOrDefault(
                    d => d.DeclaringClassSymbol.Equals(sMethod.ContainingType, SymbolEqualityComparer.Default)
                    );

                if (decl == null)
                {
                    return;
                }

                if (sMethod.Parameters.Length == 0)
                {
                    return;
                }

                if (sMethod.Parameters[0].Type.FullName() !=
                    "Microsoft.Extensions.DependencyInjection.IServiceCollection")
                {
                    return;
                }

                string configType;
                bool   isConfigurationAsync;
                bool   hasFetch;
                bool   isFetchAsync;
                if (sMethod.ReturnsVoid)
                {
                    configType           = null;
                    isConfigurationAsync = false;
                    isFetchAsync         = false;
                    hasFetch             = false;
                }
                else if (!(sMethod.ReturnType is INamedTypeSymbol returnType))
                {
                    return;
                }
                else if (returnType.FullName() == "System.Threading.Tasks.Task")
                {
                    configType           = null;
                    isConfigurationAsync = true;
                    isFetchAsync         = false;
                    hasFetch             = false;
                }
                else if (returnType.IsGenericType)
                {
                    if (returnType.ConstructedFrom.FullName() == "System.Action<T>" && returnType.TypeArguments[0].FullName() == "System.IServiceProvider")
                    {
                        configType           = null;
                        hasFetch             = true;
                        isFetchAsync         = false;
                        isConfigurationAsync = false;
                    }
                    else if (returnType.ConstructedFrom.FullName() == "System.Func<T,TResult>")
                    {
                        isConfigurationAsync = false;
                        hasFetch             = true;

                        if (returnType.TypeArguments[0].FullName() != "System.IServiceProvider")
                        {
                            return;
                        }


                        ITypeSymbol funcReturn = returnType.TypeArguments[1];
                        if (funcReturn.FullName() == "System.Threading.Tasks.Task")
                        {
                            configType   = null;
                            isFetchAsync = true;
                        }
                        else if (funcReturn is INamedTypeSymbol {
                            IsGenericType : true
                        } namedFuncReturn&&
                                 namedFuncReturn.ConstructedFrom.FullName() == "System.Threading.Tasks.Task<TResult>")
                        {
                            configType   = namedFuncReturn.TypeArguments[0].FullName();
                            isFetchAsync = true;
                        }
                        else
                        {
                            configType   = funcReturn.FullName();
                            isFetchAsync = false;
                        }
                    }
                    else if (returnType.ConstructedFrom.FullName() == "System.Threading.Tasks.Task<TResult>")
                    {
                        isConfigurationAsync = true;

                        if (returnType.TypeArguments[0] is INamedTypeSymbol {
                            IsGenericType : true
                        } asyncReturn)
                        {
                            if (asyncReturn.ConstructedFrom.FullName() == "System.Action<T>" && asyncReturn.TypeArguments[0].FullName() == "System.IServiceProvider")
                            {
                                configType   = null;
                                hasFetch     = true;
                                isFetchAsync = false;
                            }
                            else if (asyncReturn.ConstructedFrom.FullName() == "System.Func<T,TResult>" && asyncReturn.TypeArguments[0].FullName() == "System.IServiceProvider")
                            {
                                hasFetch = true;
                                ITypeSymbol funcReturn = asyncReturn.TypeArguments[1];
                                if (funcReturn.FullName() == "System.Threading.Tasks.Task")
                                {
                                    configType   = null;
                                    isFetchAsync = true;
                                }
                                else if (funcReturn is INamedTypeSymbol {
                                    IsGenericType : true
                                } namedFuncReturn&&
                                         namedFuncReturn.ConstructedFrom.FullName() == "System.Threading.Tasks.Task<TResult>")
                                {
                                    configType   = namedFuncReturn.TypeArguments[0].FullName();
                                    isFetchAsync = true;
                                }
                                else
                                {
                                    configType   = funcReturn.FullName();
                                    isFetchAsync = false;
                                }
                            }
                            else
                            {
                                return;
                            }
                        }
示例#30
0
        /// <summary>
        /// Build the list of parameters
        /// </summary>
        /// <param name="param"></param>
        /// <param name="ask"></param>
        /// <param name="declarations"></param>
        /// <param name="variables"></param>
        private void BuildParameters(Dictionary <string, ParameterExtractor.DeviceParameter> ps)
        {
            // First make a list of all possible ID's
            HashSet <string> ids = new HashSet <string>();

            foreach (var k in param.Keys)
            {
                ids.Add(k);
            }
            foreach (var k in ask.Keys)
            {
                ids.Add(k);
            }
            List <string> attr = new List <string>();
            List <string> decl = new List <string>();

            // Build a declaration for each
            foreach (var id in ids)
            {
                // Get the declarations
                string param_decl = param.ContainsKey(id) ? Code.RemoveComments(param[id]).Trim() : null;
                string ask_decl   = ask.ContainsKey(id) ? Code.RemoveComments(ask[id]).Trim() : null;
                if (!ps.ContainsKey(id))
                {
                    // Warning!
                    ConverterWarnings.Add($"Could not find definition for ID '{id}'");
                    continue;
                }
                var    info = ps[id];
                string type = GetTypeByFlag(info.FlagType);
                string name = null;

                // Build the attributes
                attr.Clear();
                foreach (var n in info.Names)
                {
                    attr.Add($"SpiceName(\"{n}\")");
                }
                attr.Add($"SpiceInfo(\"{info.Description}\")");
                List <string> declaration = new List <string>();
                decl.Clear();
                decl.Add($"[{string.Join(", ", attr)}]");

                // Create a declaration
                if (param_decl != null && ask_decl != null)
                {
                    // Let's hope it's a Parameter<>
                    string   paramGet, paramGiven;
                    string[] multiS, multiG;
                    bool     defSet = IsDefaultParameterSet(param_decl, out name, out paramGiven);
                    bool     defGet = IsDefaultGet(ask_decl, out paramGet);
                    if (defSet && defGet && name == paramGet)
                    {
                        GivenVariable.Add(paramGiven, name);
                        switch (type.ToLower())
                        {
                        case "double":
                        case "int":
                            decl.Add($"public Parameter {name} {{ get; }} = new Parameter();");
                            break;

                        default:
                            decl.Add($"public Parameter<{type}> {name} {{ get; }} = new Parameter<{type}>();");
                            break;
                        }
                    }
                    else if (IsDefaultSet(param_decl, out name) && defGet && name == paramGet)
                    {
                        decl.Add($"public {type} {name} {{ get; set; }}");
                    }
                    else if (AnySet(ref param_decl, out multiS) && AnyGet(ask_decl, out multiG))
                    {
                        decl.AddRange(new string[] { $"public {type} {id}",
                                                     "{",
                                                     "get", "{", fmtMethod(ask_decl), "}",
                                                     "set", "{", fmtMethod(param_decl), "}",
                                                     "}" });

                        // Find the first common one
                        if (multiS[0] == multiG[0])
                        {
                            name = multiS[0];
                            if (GivenVariable.ContainsValue(name))
                            {
                                switch (type.ToLower())
                                {
                                case "double":
                                case "int":
                                    decl.Add($"public Parameter {name} {{ get; }} = new Parameter();");
                                    break;

                                default:
                                    decl.Add($"public Parameter<{type}> {name} = new Parameter<{type}>();");
                                    break;
                                }
                            }
                            else
                            {
                                decl.Add($"private {type} {name};");
                            }
                        }
                    }
                    else
                    {
                        ConverterWarnings.Add($"Could not process ID '{id}'");
                        continue;
                    }
                }
                else if (param_decl != null)
                {
                    // Check for a default anyway, Spice mistakes sometimes...
                    string given;
                    if (IsDefaultParameterSet(param_decl, out name, out given))
                    {
                        GivenVariable.Add(given, name);
                        switch (type.ToLower())
                        {
                        case "double":
                        case "int":
                            decl.Add($"public Parameter {name} {{ get;}} = new Parameter();");
                            break;

                        default:
                            decl.Add($"public Parameter<{type}> {name} {{ get; }} = new Parameter<{type}>();");
                            break;
                        }
                    }
                    else if (IsDefaultSet(param_decl, out name))
                    {
                        decl.Add($"public {type} {name} {{ get; set; }}");
                    }
                    else
                    {
                        string[] names;
                        AnySet(ref param_decl, out names);
                        decl.AddRange(new string[] { $"public void Set{id}({type} value)", "{", fmtMethod(param_decl), "}" });
                    }
                }
                else if (ask_decl != null)
                {
                    if (IsDefaultGet(ask_decl, out name))
                    {
                        decl.Add($"public {type} {name} {{ get; private set; }}");
                    }
                    else
                    {
                        decl.AddRange(new string[] { $"public {type} Get{id}(Circuit ckt)", "{", fmtMethod(ask_decl), "}" });
                    }
                }
                else
                {
                    throw new Exception("Invalid declaration(?)");
                }

                // Store
                if (name != null)
                {
                    Variables.Add(name);
                    Declarations.Add(name, string.Join(Environment.NewLine, decl));
                }
                else
                {
                    Methods.Add(string.Join(Environment.NewLine, decl));
                }
            }
        }
示例#31
0
	void ProcessInterface (string iface)
	{
		bool need_close = iface.IndexOf ("{") != -1;
		var cols = iface.Split ();
		string line;

		//Console.WriteLine ("**** {0} ", iface);
		types.Add (cols [1]);
		if (extraAttribute != null)
			gencs.Write ("\n\t[{0}]", extraAttribute);
		if (cols.Length >= 4)
			gencs.WriteLine ("\n\t[BaseType (typeof ({0}))]", cols [3]);
		gencs.WriteLine ("\t{0}interface {1} {{", limit == null ? "" : "public partial ", cols [1]);

		//while ((line = r.ReadLine ()) != null && (need_close && !line.StartsWith ("}"))){
		//	if (line == "{")
		//		need_close = true;
		//}
		line = r.ReadLine ();
		if (line == "{")
			need_close = true;
		while (line != null && (need_close && line != "}"))
			line = r.ReadLine ();

		var decl = new Declarations (gencs);
		while ((line = r.ReadLine ()) != null && !line.StartsWith ("@end")){
			string full = "";
				
			while ((line = r.ReadLine ()) != null && !line.StartsWith ("@end")){
				full += line;
				if (full.IndexOf (';') != -1){
					full = full.Replace ('\n', ' ');
					decl.Add (ProcessDeclaration (false, full, false));
					full = "";
				}
			}
			break;
		}
		decl.Generate (extraAttribute);
		gencs.WriteLine ("\t}");
	}
示例#32
0
 public ModuleInstance(IModuleDeclaration decl)
 {
     Name = decl.Name;
     Declarations.Add(decl);
 }
示例#33
0
	void ProcessProtocol (string proto)
	{
		string [] d = proto.Split (new char [] { ' ', '<', '>'});
		string line;

		types.Add (d [1]);
		if (extraAttribute != null)
			gencs.WriteLine ("\n\t[{0}]", extraAttribute);
		gencs.WriteLine ("\n\t[BaseType (typeof ({0}))]", d.Length > 2 ? d [2] : "NSObject");
		gencs.WriteLine ("\t[Model]");
		gencs.WriteLine ("\tinterface {0} {{", d [1]);
		bool optional = false;
		
		var decl = new Declarations (gencs);
		while ((line = r.ReadLine ()) != null && !line.StartsWith ("@end")){
			if (line.StartsWith ("@optional"))
				optional = true;

			string full = "";
			while ((line = r.ReadLine ()) != null && !line.StartsWith ("@end")){
				full += line;
				if (full.IndexOf (';') != -1){
					full = full.Replace ('\n', ' ');
					decl.Add (ProcessDeclaration (true, full, optional));
					full = "";
				}
			}
			if (line.StartsWith ("@end"))
				break;
		}
		decl.Generate (extraAttribute);
		gencs.WriteLine ("\t}");
	}
        /// <summary>
        /// The object factory for a particular data collection instance.
        /// </summary>
        public virtual void CreateObjectsFromData(Declarations declarations, System.Data.DataSet data)
        {
            // Do nothing if we have nothing
            if (data == null || data.Tables.Count == 0 || data.Tables[0].Rows.Count == 0) return;

            // Create a local variable for the new instance.
            Declaration newobj = null;
            // Create a local variable for the data row instance.
            System.Data.DataRow dr = null;

            // Iterate through the table rows
            for (int i = 0; i<data.Tables[0].Rows.Count; i++)
            {
                // Get a reference to the data row
                dr = data.Tables[0].Rows[i];
                // Create a new object instance
                newobj = System.Activator.CreateInstance(declarations.ContainsType[0]) as Declaration;
                // Let the instance set its own members
                newobj.SetMembers(ref dr);
                // Add the new object to the collection instance
                declarations.Add(newobj);
            }
        }