Exemplo n.º 1
0
        // No visit, return empty BlockExpressioNode
        public override SubExpressionGraph Visit(FunctionDefinitionNode node)
        {
            var sub_graph = new SubExpressionGraph();

            sub_graph.LastNode = new BlockExpressionNode();
            return(sub_graph);
        }
Exemplo n.º 2
0
        public override DynValue Visit(FunctionDefinitionNode scriptFunctionDefinitionNode)
        {
            var name = scriptFunctionDefinitionNode.Name;

            var fn = new ScriptFunction(
                scriptFunctionDefinitionNode.StatementList,
                scriptFunctionDefinitionNode.ParameterNames
                );

            if (name != null)
            {
                if (Environment.LocalScope != Environment.GlobalScope)
                {
                    throw new RuntimeException("Attempt to define a named function in local scope.",
                                               scriptFunctionDefinitionNode.Line);
                }

                Environment.RegisterFunction(
                    name,
                    fn
                    );
            }

            foreach (var kvp in Environment.LocalScope.Members)
            {
                fn.Closures.Add(kvp.Key, kvp.Value);
            }

            return(new DynValue(fn));
        }
Exemplo n.º 3
0
        private static PythonNode Wrap(FunctionDefinition stmt, PythonNode parent)
        {
            var result = new FunctionDefinitionNode(stmt)
            {
                Parent = parent
            };

            if (!stmt.Name.IsNullOrEmpty())
            {
                result.Value = stmt.Name;
            }
            if (stmt.Decorators != null)
            {
                foreach (var exp in stmt.Decorators)
                {
                    result.AddChild(Wrap(exp, result));
                }
            }
            foreach (var param in stmt.Parameters)
            {
                result.AddChild(Wrap(param, result));
            }
            result.AddChild(Wrap(stmt.Body, result));
            return(result);
        }
Exemplo n.º 4
0
        // The following methods are used to insert methods to the bottom of the AST and convert operator to these method calls
        // to support replication on operators
        private static void InsertUnaryOperationMethod(Core core, CodeBlockNode root, UnaryOperator op, PrimitiveType r, PrimitiveType operand)
        {
            FunctionDefinitionNode funcDefNode = new FunctionDefinitionNode();

            funcDefNode.Access          = CompilerDefinitions.AccessModifier.Public;
            funcDefNode.IsAssocOperator = true;
            funcDefNode.IsBuiltIn       = true;
            funcDefNode.Name            = Op.GetUnaryOpFunction(op);
            funcDefNode.ReturnType      = new Type()
            {
                Name = core.TypeSystem.GetType((int)r), UID = (int)r
            };
            ArgumentSignatureNode args = new ArgumentSignatureNode();

            args.AddArgument(new VarDeclNode()
            {
                Access       = CompilerDefinitions.AccessModifier.Public,
                NameNode     = AstFactory.BuildIdentifier("%param"),
                ArgumentType = new Type {
                    Name = core.TypeSystem.GetType((int)operand), UID = (int)operand
                }
            });
            funcDefNode.Signature = args;

            CodeBlockNode  body  = new CodeBlockNode();
            IdentifierNode param = AstFactory.BuildIdentifier("%param");

            body.Body.Add(AstFactory.BuildReturnStatement(new UnaryExpressionNode()
            {
                Expression = param, Operator = op
            }));
            funcDefNode.FunctionBody = body;
            root.Body.Add(funcDefNode);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Ensures that dispose method node is created for this empty type.
        /// </summary>
        /// <param name="module">Reference module</param>
        public void EnsureDisposeMethod(CLRDLLModule module)
        {
            foreach (var item in ClassNode.funclist)
            {
                if (item.Name == ProtoCore.DSDefinitions.Keyword.Dispose)
                {
                    return; //Dispose method is already present.
                }
            }
            bool resetModule = false;

            if (Module == null)
            {
                Module      = module;
                resetModule = true;
            }
            AssociativeNode        node = ParseMethod(mDisposeMethod);
            FunctionDefinitionNode func = node as FunctionDefinitionNode;

            if (func != null)
            {
                func.Name            = ProtoCore.DSDefinitions.Keyword.Dispose;
                func.IsStatic        = false;
                func.IsAutoGenerated = true;
                ClassNode.funclist.Add(func);
            }
            if (resetModule)
            {
                Module = null;
            }
        }
Exemplo n.º 6
0
        private void AddBinding(MethodInfo method, LinkableFunctionAttribute attribute, VMFunctionDelegate implementation)
        {
            FunctionDefinitionNode def = new FunctionDefinitionNode(
                name: attribute.Name ?? method.Name,
                returnType: new TypeSpecifierParseNode("int", PointerMode.NotAPointer), // TODO
                parameters: FunctionAttributeToDeclarations(attribute),
                body: new BodyNode(),
                isExported: true,
                isDrop: false
                );

            Binding binding = new Binding {
                Prototype      = def,
                Implementation = new VMFunction {
                    ReturnValueSize    = sizeof(int),                         // TODO
                    ArgumentMemorySize = def.Parameters.Length * sizeof(int), // TODO
                    Delegate           = implementation
                }
            };

            _bindings[method.Name] = binding;

            Symbol symbol = new Symbol();

            symbol.Node       = def;
            symbol.SourceFile = method.Module.FullyQualifiedName;
            _tokenMap[def]    = symbol;
        }
        public override void Visit(FunctionDefinitionNode node)
        {
            base.Visit(node);

            if (!ReferenceEquals(node.Parameters, null))
            {
                foreach (var parameter in node.Parameters)
                {
                    if (!ReferenceEquals(parameter, null))
                    {
                        parameter.Accept(this);
                    }
                }
            }

            if (!ReferenceEquals(node.ResultType, null))
            {
                node.ResultType.Accept(this);
            }

            if (!ReferenceEquals(node.Body, null))
            {
                node.Body.Accept(this);
            }
        }
Exemplo n.º 8
0
        public override AssociativeNode VisitFunctionDefinitionNode(FunctionDefinitionNode node)
        {
            var nodeList = node.FunctionBody.Body.Select(astNode => astNode.Accept(this)).ToList();

            node.FunctionBody.Body = nodeList;
            return(node);
        }
Exemplo n.º 9
0
        public void Validate(LValue targetLValue, FunctionDefinitionNode function)
        {
            _targetLValue = targetLValue;
            _isTargetCurrentlyAssigned = false;

            function.Body.AcceptStatementVisitor(this);
        }
Exemplo n.º 10
0
        private AssociativeNode ParseAndRegisterFunctionPointer(bool isDisposable, ref bool hasDisposeMethod, MethodInfo m)
        {
            AssociativeNode        node = ParseMethod(m);
            FunctionDefinitionNode func = node as FunctionDefinitionNode;

            if (func != null)
            {
                //Rename the Dispose method to _Dispose, as required by DS.
                if (isDisposable && isDisposeMethod(m))
                {
                    hasDisposeMethod     = true;
                    func.Name            = ProtoCore.DSDefinitions.Keyword.Dispose;
                    func.IsStatic        = false;
                    func.IsAutoGenerated = true;
                }

                RegisterFunctionPointer(func.Name, m, func.ReturnType);
            }
            else if (node is ConstructorDefinitionNode)
            {
                ConstructorDefinitionNode constr = node as ConstructorDefinitionNode;
                RegisterFunctionPointer(constr.Name, m, constr.ReturnType);
            }
            return(node);
        }
 public BorrowAssignmentLifetimeValidator(FunctionDefinitionNode function, IErrorManager errors, ExpressionTypeManager types, ScopeManager scopes)
 {
     _function         = function;
     _errors           = errors;
     _scopes           = scopes;
     _types            = types;
     _lifetimeResolver = new BorrowPointerLifetimeResolver(scopes);
 }
 public void VisitFunctionDefinition(FunctionDefinitionNode node)
 {
     node.ReturnType = _processor.ProcessReplacement(node.ReturnType);
     for (int i = 0, ilen = node.Parameters.Length; i < ilen; ++i)
     {
         node.Parameters[i] = _processor.ProcessReplacement(node.Parameters[i]);
     }
 }
Exemplo n.º 13
0
        public override void Visit(FunctionDefinitionNode node)
        {
            var tmp = _currentFunction;

            _currentFunction = node;
            base.Visit(node);
            _currentFunction = tmp;
        }
Exemplo n.º 14
0
        public void Process(FunctionDefinitionNode function)
        {
            SyntaxTreeDelegator      childrenDelegator = new SyntaxTreeDelegator();
            StatementChildrenVisitor statementVisitor  = new StatementChildrenVisitor(_delegator, childrenDelegator);

            childrenDelegator.StatementVisitor  = statementVisitor;
            childrenDelegator.ExpressionVisitor = this;
            function.Body.VisitStatements(statementVisitor);
        }
Exemplo n.º 15
0
 //check if body returns the same as set type
 public override void Visit(FunctionDefinitionNode node)
 {
     base.Visit(node);
     if (!node.ResultType.Equals(node.Body.ExpressionType, false))
     {
         throw new TypeCheckException("Body doesn't return the same type as set type.");
     }
     node.ExpressionType = NamedTypeNode.VoidType();
 }
        public override void Visit(FunctionDefinitionNode node)
        {
            variableSymbolTable.OpenBlock();

            functionSymbolTable.Insert(node.Name, node);
            base.Visit(node);

            variableSymbolTable.CloseBlock();
        }
Exemplo n.º 17
0
 public void VisitFunctionDefinition(FunctionDefinitionNode node)
 {
     _visitor.VisitTopLevelStatement(node);
     node.ReturnType.AcceptSyntaxTreeVisitor(_childrenVisitor);
     for (int i = 0, ilen = node.Parameters.Length; i < ilen; ++i)
     {
         node.Parameters[i].AcceptSyntaxTreeVisitor(_childrenVisitor);
     }
     node.Body.AcceptSyntaxTreeVisitor(_childrenVisitor);
 }
Exemplo n.º 18
0
 public void Analyze(FunctionDefinitionNode function)
 {
     _currentScope = _scopeManager.OuterScope;
     foreach (DeclarationNode parameter in function.Parameters)
     {
         VisitDeclaration(parameter);
     }
     PushScope();
     function.Body.VisitStatements(this);
     PopScope();
 }
Exemplo n.º 19
0
        /// <summary>
        /// Returns the has id of a function signature given the name and argument types
        /// </summary>
        /// <param name="functionDef"></param>
        /// <returns></returns>
        public static int GetFunctionHash(FunctionDefinitionNode functionDef)
        {
            Validity.Assert(null != functionDef);
            string functionDescription = functionDef.Name;

            foreach (VarDeclNode argNode in functionDef.Signature.Arguments)
            {
                functionDescription += argNode.ArgumentType.ToString();
            }
            return(functionDescription.GetHashCode());
        }
Exemplo n.º 20
0
        public int GetFunctionIndex(FunctionDefinitionNode node)
        {
            int index;

            if (!FunctionTable.TryGetValue(node.Name, out index))
            {
                index = FunctionTable.Count;
                UndefinedFunctions.Add(node.Name, index);
                FunctionTable.Add(node.Name, index);
            }
            return(index);
        }
Exemplo n.º 21
0
        public override void Visit(FunctionDefinitionNode node)
        {
            // create this function backend object
            var parametersBitmap = node.Parameters.Select(p => p.NestedUse).ToArray();
            var enclosedIn       = (functions.Count > 0) ? functions.Peek() : null;       // peek od stack - parent function

            node.BackendFunction = new Function(node.Name, parametersBitmap, enclosedIn); // no name mangling for now - no function name overloading
            // continue visiting, place this function on stack, remove it when le
            functions.Push(node.BackendFunction);
            base.Visit(node);
            functions.Pop();
        }
Exemplo n.º 22
0
        public void Process(FunctionDefinitionNode function, IReplacementListener listener)
        {
            ProcessReplacementsVisitorChain visitorChain = new ProcessReplacementsVisitorChain(this, listener, isPostOrder: true);
            ParseTreeChildrenVisitor        parseTreeChildrenVisitor
                = new ParseTreeChildrenVisitor(null, visitorChain.ReplacementVisitor, visitorChain.ChildrenVisitor);
            ProcessParseTreeReplacementsVisitor parseTreeReplacementsVisitor
                = new ProcessParseTreeReplacementsVisitor(this, listener);

            visitorChain.ExpressionChildrenVisitor.ExtensionChildrenVisitor = new ParseTreeVisitorExtension(parseTreeChildrenVisitor);
            visitorChain.ExpressionReplacementsVisitor.ExtensionVisitor     = new ParseTreeVisitorExtension(parseTreeReplacementsVisitor);
            visitorChain.ProcessReplacements(function);
        }
Exemplo n.º 23
0
 public ILFunction Build(FunctionDefinitionNode functionDefinitionNode)
 {
     return(new ILFunction {
         ArgumentMemorySize = _layout.ArgumentsSize,
         ReturnValueSize = _layout.ReturnValueSize,
         MaxStackSize = _maxStackWorkOffset,
         Code = _instructions.ToArray(),
         Symbols = _addressToTokenMap,
         StringInstructions = _stringInstructions.ToArray(),
         VariableSymbols = _layout.Variables.ToDictionary(kvp => kvp.Value, kvp => kvp.Key),
         InstructionsReferencingFunctionAddresses = _instructionsReferencingFunctionAddresses.ToArray()
     });
 }
Exemplo n.º 24
0
        public void Process(FunctionDefinitionNode function, IReplacementListener listener)
        {
            // TODO: Helper class to reduce repeating of this setup code.
            ProcessReplacementsVisitorChain visitorChain = new ProcessReplacementsVisitorChain(this, listener);
            ParseTreeChildrenVisitor        parseTreeChildrenVisitor
                = new ParseTreeChildrenVisitor(visitorChain.ReplacementVisitor, null, visitorChain.ChildrenVisitor);
            ProcessParseTreeReplacementsVisitor parseTreeReplacementsVisitor
                = new ProcessParseTreeReplacementsVisitor(this, listener);

            visitorChain.ExpressionChildrenVisitor.ExtensionChildrenVisitor = new ParseTreeVisitorExtension(parseTreeChildrenVisitor);
            visitorChain.ExpressionReplacementsVisitor.ExtensionVisitor     = new ParseTreeVisitorExtension(parseTreeReplacementsVisitor);

            visitorChain.ProcessReplacements(function);
        }
Exemplo n.º 25
0
        private ClassDeclNode ParseEnumType(Type type, string alias)
        {
            //TODO: For now Enum can't be suppressed.
            Validity.Assert(type.IsEnum, "Non enum type is being imported as enum!!");

            string classname = alias;

            if (classname == null | classname == string.Empty)
            {
                classname = CLRObjectMarshler.GetTypeName(type);
            }

            ProtoCore.AST.AssociativeAST.ClassDeclNode classnode = CreateEmptyClassNode(classname);
            classnode.ExternLibName = Module.Name;
            classnode.className     = classname;
            classnode.Name          = type.Name;

            FieldInfo[] fields = type.GetFields();
            foreach (var f in fields)
            {
                if (f.FieldType != type)
                {
                    continue;
                }

                VarDeclNode variable = ParseFieldDeclaration(f);
                if (null == variable)
                {
                    continue;
                }
                variable.IsStatic = true;
                classnode.varlist.Add(variable);
                FunctionDefinitionNode func = ParseFieldAccessor(f);
                if (null != func)
                {
                    func.IsStatic = true;
                    RegisterFunctionPointer(func.Name, f, null, func.ReturnType);
                    classnode.funclist.Add(func);
                }
            }

            //Get all the attributes on this type and set it to the classnode.
            FFIClassAttributes cattrs = new FFIClassAttributes(type);

            classnode.ClassAttributes = cattrs;
            SetTypeAttributes(type, cattrs);

            return(classnode);
        }
Exemplo n.º 26
0
        public void Process(FunctionDefinitionNode function)
        {
            SyntaxTreeDelegator visitor            = new SyntaxTreeDelegator();
            StatementDelegator  statementDelegator = new StatementDelegator();

            statementDelegator.DeclarationVisitor = this;
            visitor.StatementVisitor = statementDelegator;

            SyntaxTreeDelegator      childrenVisitor          = new SyntaxTreeDelegator();
            StatementChildrenVisitor statementChildrenVisitor = new StatementChildrenVisitor(visitor, childrenVisitor);

            childrenVisitor.StatementVisitor = statementChildrenVisitor;

            function.Body.VisitStatements(statementChildrenVisitor);
        }
Exemplo n.º 27
0
        public void VisitFunctionDefinition(FunctionDefinitionNode node)
        {
            // Return value
            IType returnType = ((TypeSpecifierNode)node.ReturnType).Type;

            _returnValueSize = _typeSizeManager.GetSize(returnType);
            _currentOffset  += _returnValueSize;

            foreach (DeclarationNode decl in node.Parameters)
            {
                VisitDeclaration(decl);
            }
            _argumentsSize = _currentOffset - _returnValueSize;
            VisitBody(node.Body);
        }
Exemplo n.º 28
0
        public void Process(FunctionDefinitionNode function)
        {
            if (TypeUtil.IsVoid(function.ReturnType))
            {
                return;
            }

            _didReturn = false;
            VisitBody(function.Body);

            if (!_didReturn)
            {
                _errors.AddError("Not all code paths return a value", function.Body);
            }
        }
Exemplo n.º 29
0
        public void RegisterFunction(FunctionDefinitionNode node)
        {
            if (DefinedFunctions.ContainsKey(node.Name))
            {
                return;
            }

            int index = FunctionTable.Count;

            DefinedFunctions.Add(node.Name, index);
            FunctionTable.Add(node.Name, index);
            if (node.IsExported)
            {
                ExportedFunctions.Add(new KeyValuePair <string, int>(node.Name, index));
            }
        }
Exemplo n.º 30
0
        void functiondecl(out Node node)
        {
            FunctionDefinitionNode funcDecl = new FunctionDefinitionNode();

            ProtoCore.Type rtype = new ProtoCore.Type(); rtype.Name = "var"; rtype.UID = 0;
            Expect(18);
            Expect(1);
            funcDecl.Name = t.val;
            if (la.kind == 36)
            {
                Get();
                ReturnType(out rtype);
            }
            funcDecl.ReturnType = rtype;
            Expect(8);
            if (la.kind == 1 || la.kind == 25)
            {
                ArgumentSignatureNode args = new ArgumentSignatureNode();
                Node argdecl;
                ArgDecl(out argdecl);
                args.AddArgument(argdecl as VarDeclNode);
                while (la.kind == 30)
                {
                    Get();
                    ArgDecl(out argdecl);
                    args.AddArgument(argdecl as VarDeclNode);
                }
                funcDecl.Signature = args;
            }
            Expect(9);
            isGlobalScope = false;
            Expect(32);
            funcDecl.FunctionBody = new CodeBlockNode();
            NodeList body = new NodeList();

            stmtlist(out body);
            Expect(33);
            funcDecl.localVars         = localVarCount;
            funcDecl.FunctionBody.Body = body;
            node = funcDecl;

            isGlobalScope = true;
            localVarCount = 0;
        }
		public virtual Value evaluate(Context cx, FunctionDefinitionNode node)
		{
			return evaluate(node, cx, "FunctionDefinitionNode");
		}
		private Value evaluate(FunctionDefinitionNode node, Context cx, System.String name)
		{
			if ((node.name != null) && (node.name.identifier.name != null))
			{
				output("<" + name + " name=\"" + node.name.identifier.name + "\">");
			}
			else
			{
				output("<" + name + ">");
			}
			indent_Renamed_Field++;
			if (node.attrs != null)
			{
				node.attrs.evaluate(cx, this);
			}
			if (node.fexpr != null)
			{
				node.fexpr.evaluate(cx, this);
			}
			indent_Renamed_Field--;
			output("</" + name + ">");
			return null;
		}