예제 #1
0
        /// <summary>Adds a method that was found into this classes set of methods to compile.</summary>
        /// <param name="fragment">The first fragment of the method, used for generating errors. This gives a valid line number.</param>
        /// <param name="body">The block of code for this method.</param>
        /// <param name="name">The name of the method. Null if anonymous is true.</param>
        /// <param name="anonymous">True if this method is an anonymous one and requires a name.</param>
        /// <param name="parameters">The set of parameters for this method.</param>
        /// <param name="returnType">The type that this method returns.</param>
        /// <param name="isPublic">True if this is a public method; false for private.</param>
        /// <returns>The first fragment following the method, if there is one.</returns>
        protected virtual CodeFragment AddFoundMethod(CodeFragment fragment, CodeFragment body, string name, bool anonymous, BracketFragment parameters, TypeFragment returnType, bool isPublic)
        {
            if (body == null)
            {
                fragment.Error("Invalid function definition (" + name + "). The content block {} is missing or isnt valid.");
            }

            if (anonymous)
            {
                name = "Compiler-Generated-$" + AnonymousCount;
                AnonymousCount++;
            }

            // The following is the explicit code block for this function:
            BracketFragment codeBlock = (BracketFragment)body;
            CompiledMethod  cMethod   = new CompiledMethod(this, name, parameters, codeBlock, returnType, isPublic);
            MethodOverloads set       = MakeOrFind(name, cMethod.Builder.ReturnType);
            CodeFragment    next      = body.NextChild;

            if (anonymous)
            {
                CodeFragment newChild = DynamicMethodCompiler.Compile(cMethod, name, set.ReturnType, new ThisOperation(cMethod));
                newChild.AddAfter(body);
            }

            body.Remove();
            set.AddMethod(cMethod);
            FindMethods(codeBlock);

            return(next);
        }
예제 #2
0
        /// <summary>Finds any other entries in the given code fragment.</summary>
        /// <param name="fragment">The fragment to search.</param>
        public void FindOperations(CodeFragment fragment)
        {
            CodeFragment child = fragment.FirstChild;
            CodeFragment next  = null;

            BracketFragment ovrs = null;

            while (child != null)
            {
                next = child.NextChild;

                if (child.IsParent)
                {
                    // Got one!
                    // Just gotta transfer it into the method body of OnScriptReady:

                    if (ovrs == null)
                    {
                        ovrs = GetStartMethod().CodeBlock;
                    }

                    // Remove it as a child:
                    child.Remove();

                    // Remove the word 'var' to ensure its properties are globally scoped.
                    GloballyScope(child);

                    // Add it to start method:
                    ovrs.AddChild(child);
                }

                child = next;
            }
        }
		public override AddResult AddTo(CodeFragment to,CodeLexer sr){
			if(to.LastChild==null){
				Error("A property (."+Value+") was found in an unexpected place.");
			}
			// Replace the last child with *THIS*:
			of=to.LastChild;
			of.Remove();
			to.AddChild(this);
			return AddResult.Ok;
		}
예제 #4
0
        public override AddResult AddTo(CodeFragment to, CodeLexer sr)
        {
            if (Bracket == '[')
            {
                if (to.LastChild == null)
                {
                    Error("Unexpected indexing. must be something[index].");
                }
                else
                {
                    CodeFragment var = to.LastChild;
                    var.Remove();

                    return(new IndexFragment(this, var).AddTo(to, sr));
                }
            }
            else if (Bracket == '{' && to.LastChild != null)
            {
                // new TYPE[]{default,default..};

                if (to.LastChild.GetType() == typeof(VariableFragment) && ((VariableFragment)(to.LastChild)).Value == "new")
                {
                    VariableFragment var = (VariableFragment)(to.LastChild);

                    if (var.GivenType == null)
                    {
                        Error("new must always be followed by a type name.");
                    }
                    else if (!var.GivenType.IsArray)
                    {
                        Error("new Type{} only works when Type is an array and curley brackets define it's default values e.g. new int[]{1,2}");
                    }
                    else
                    {
                        var.Remove();
                        return(new ArrayFragment(var.GivenType, this).AddTo(to, sr));
                    }
                }
            }
            else if (Bracket == '(' && to.LastChild != null)
            {
                Type type = to.LastChild.GetType();

                if (type == typeof(IndexFragment) || type == typeof(PropertyFragment) || (type == typeof(VariableFragment) && !((VariableFragment)(to.LastChild)).IsKeyword()))
                {
                    // Method call!
                    CodeFragment meth = to.LastChild;
                    meth.Remove();

                    return(new MethodFragment(this, meth).AddTo(to, sr));
                }
            }

            return(base.AddTo(to, sr));
        }
 public override AddResult AddTo(CodeFragment to, CodeLexer sr)
 {
     if (to.LastChild == null)
     {
         Error("A property (." + Value + ") was found in an unexpected place.");
     }
     // Replace the last child with *THIS*:
     of = to.LastChild;
     of.Remove();
     to.AddChild(this);
     return(AddResult.Ok);
 }
예제 #6
0
        public override CompiledFragment Compile(CompiledMethod method)
        {
            if (!IsParent)
            {
                return(null);
            }

            CodeFragment child = FirstChild;

            while (child != null)
            {
                CodeFragment     next  = child.NextChild;
                CompiledFragment cfrag = child.Compile(method);

                if (cfrag != null)
                {
                    cfrag.AddAfter(child);
                }

                child.Remove();
                child = next;
            }

            if (GivenType != null)
            {
                Type toType = GivenType.FindType(method.Script);

                if (toType == null)
                {
                    Error("Type not found: " + GivenType.ToString() + ".");
                }

                CompiledFragment compiledKid = (CompiledFragment)FirstChild;
                CompiledFragment result      = Types.TryCast(method, compiledKid, toType);

                if (result == null)
                {
                    Error("Cannot cast " + compiledKid.OutputType() + " to " + toType + ".");
                }

                return(result);
            }

            return((CompiledFragment)FirstChild);
        }
예제 #7
0
        public override CompiledFragment Compile(CompiledMethod method)
        {
            if (!IsParent)
            {
                return(null);
            }

            CodeFragment child = FirstChild;

            while (child != null)
            {
                CodeFragment     next  = child.NextChild;
                CompiledFragment cfrag = child.Compile(method);

                if (cfrag != null)
                {
                    cfrag.AddAfter(child);
                }

                child.Remove();
                child = next;
            }

            // Is this a cast?
            if (GivenType != null)
            {
                // Get the type being cast to:
                Type toType = GivenType.FindType(method.Script);

                if (toType == null)
                {
                    Error("Type to cast to was not found: " + GivenType.ToString() + ".");
                }

                // Get the object being cast:
                CompiledFragment compiledKid = (CompiledFragment)FirstChild;

                // Create a cast operation with it:
                return(new CastOperation(method, compiledKid, toType));
            }

            return((CompiledFragment)FirstChild);
        }
		/// <summary>Adds a method that was found into this classes set of methods to compile.</summary>
		/// <param name="fragment">The first fragment of the method, used for generating errors. This gives a valid line number.</param>
		/// <param name="body">The block of code for this method.</param>
		/// <param name="name">The name of the method. Null if anonymous is true.</param>
		/// <param name="anonymous">True if this method is an anonymous one and requires a name.</param>
		/// <param name="parameters">The set of parameters for this method.</param>
		/// <param name="returnType">The type that this method returns.</param>
		/// <param name="isPublic">True if this is a public method; false for private.</param>
		/// <returns>The first fragment following the method, if there is one.</returns>
		protected virtual CodeFragment AddFoundMethod(CodeFragment fragment,CodeFragment body,string name,bool anonymous,BracketFragment parameters,TypeFragment returnType,bool isPublic){
			
			if(body==null){
				fragment.Error("Invalid function definition ("+name+"). The content block {} is missing or isnt valid.");
			}
			
			if(anonymous){
				name="Compiler-Generated-$"+AnonymousCount;
				AnonymousCount++;
			}
			
			// The following is the explicit code block for this function:
			BracketFragment codeBlock=(BracketFragment)body;
			CompiledMethod cMethod=new CompiledMethod(this,name,parameters,codeBlock,returnType,isPublic);
			MethodOverloads set=MakeOrFind(name,cMethod.Builder.ReturnType);
			CodeFragment next=body.NextChild;
			
			if(anonymous){
				CodeFragment newChild=DynamicMethodCompiler.Compile(cMethod,name,set.ReturnType,new ThisOperation(cMethod));
				newChild.AddAfter(body);
			}
			
			body.Remove();
			set.AddMethod(cMethod);
			FindMethods(codeBlock);
			
			return next;
			
		}
 /// <summary>Adds this code fragment as a child before the given one.</summary>
 /// <param name="frag">The fragment to add this before.</param>
 public void AddBefore(CodeFragment frag)
 {
     AddAfter(frag);
     frag.Remove();
     frag.AddAfter(this);
 }
예제 #10
0
        /// <summary>Finds all classes within the given code fragment, identified with 'class'.</summary>
        /// <param name="frag">The fragment to search.</param>
        private void FindClasses(CodeFragment frag)
        {
            CodeFragment child = frag.FirstChild;

            while (child != null)
            {
                CodeFragment next = child.NextChild;

                if (child.IsParent)
                {
                    FindClasses(child);
                }
                else if (child.GetType() == typeof(VariableFragment))
                {
                    VariableFragment vfrag = (VariableFragment)child;

                    if (vfrag.Value == "class")
                    {
                        bool isPublic;
                        Modifiers.Handle(vfrag, out isPublic);

                        Type         baseType  = null;
                        CodeFragment nameBlock = vfrag.NextChild;

                        if (nameBlock == null || nameBlock.GetType() != typeof(VariableFragment))
                        {
                            vfrag.Error("Class keyword used but no class name given.");
                        }

                        vfrag.Remove();
                        vfrag = (VariableFragment)nameBlock;

                        if (vfrag.IsKeyword())
                        {
                            vfrag.Error("Can't use keywords for class names.");
                        }

                        string name = vfrag.Value;

                        if (Types.ContainsKey(name))
                        {
                            vfrag.Error("Cannot redefine class " + name + " - it already exists in this scope.");
                        }

                        if (vfrag.GivenType != null)
                        {
                            baseType = vfrag.GivenType.FindType(this);
                        }

                        if (baseType == null)
                        {
                            baseType = typeof(object);
                        }

                        CodeFragment cblock = vfrag.NextChild;

                        if (cblock == null || cblock.GetType() != typeof(BracketFragment))
                        {
                            vfrag.Error("Class " + name + " is missing it's code body. Correct syntax: class " + name + "{ .. }.");
                        }

                        next = cblock.NextChild;
                        vfrag.Remove();
                        cblock.Remove();
                        Types.Add(name, new CompiledClass(cblock, this, name, baseType, isPublic));
                    }
                }

                child = next;
            }
        }
예제 #11
0
        /// <summary>Finds methods within the given fragment by looking for 'function'.</summary>
        /// <param name="fragment">The fragment to search.</param>
        public void FindMethods(CodeFragment fragment)
        {
            CodeFragment child = fragment.FirstChild;

            while (child != null)
            {
                CodeFragment next = child.NextChild;

                if (child.IsParent)
                {
                    FindMethods(child);
                }

                try{
                    if (child.GetType() == typeof(VariableFragment))
                    {
                        VariableFragment vfrag    = ((VariableFragment)child);
                        CodeFragment     toRemove = null;
                        string           Value    = vfrag.Value;

                        if (Value == "function")
                        {
                            // Found a function.
                            bool isPublic;
                            Modifiers.Handle(vfrag, out isPublic);

                            // The return type could be on the function word (function:String{return "hey!";})
                            TypeFragment returnType = child.GivenType;

                            toRemove = child;
                            child    = child.NextChild;

                            if (child == null)
                            {
                                fragment.Error("Keyword 'function' can't be used on its own.");
                            }

                            toRemove.Remove();
                            string          name       = "";
                            bool            anonymous  = false;
                            BracketFragment parameters = null;

                            if (child.GetType() == typeof(MethodFragment))
                            {
                                MethodFragment method = (MethodFragment)child;
                                name       = ((VariableFragment)(method.MethodName)).Value;
                                parameters = method.Brackets;
                                toRemove   = child;
                                child      = child.NextChild;
                                toRemove.Remove();
                                returnType = method.GivenType;
                            }
                            else if (child.GetType() == typeof(VariableFragment))
                            {
                                // Found the name
                                vfrag = (VariableFragment)child;

                                if (vfrag.IsKeyword())
                                {
                                    vfrag.Error("Keywords cannot be used as function names (" + vfrag.Value + ").");
                                }

                                name = vfrag.Value;

                                if (returnType == null)
                                {
                                    returnType = child.GivenType;
                                }

                                toRemove = child;
                                child    = child.NextChild;
                                toRemove.Remove();

                                if (child == null)
                                {
                                    fragment.Error("Invalid function definition (" + name + "). All brackets are missing or arent valid.");
                                }
                            }
                            else
                            {
                                anonymous = true;
                            }

                            next = AddFoundMethod(fragment, child, name, anonymous, parameters, returnType, isPublic);
                        }
                    }
                    else if (child.GetType() == typeof(MethodFragment))
                    {
                        // Looking for anonymous methods ( defined as function() )
                        MethodFragment method = (MethodFragment)child;

                        if (method.MethodName.GetType() == typeof(VariableFragment))
                        {
                            VariableFragment methodName = ((VariableFragment)(method.MethodName));
                            string           name       = methodName.Value;

                            if (name == "function")
                            {
                                // Found an anonymous function, function():RETURN_TYPE{}.
                                // Note that function{}; is also possible and is handled above.
                                CodeFragment toRemove = child;
                                child = child.NextChild;
                                toRemove.Remove();

                                next = AddFoundMethod(fragment, child, null, true, method.Brackets, method.GivenType, true);
                            }
                            else if (method.Brackets != null)
                            {
                                FindMethods(method.Brackets);
                            }
                        }
                        else if (method.Brackets != null)
                        {
                            FindMethods(method.Brackets);
                        }
                    }
                }catch (CompilationException e) {
                    if (e.LineNumber == -1 && child != null)
                    {
                        // Setup line number:
                        e.LineNumber = child.GetLineNumber();
                    }

                    // Rethrow:
                    throw e;
                }

                child = next;
            }
        }
예제 #12
0
        /// <summary>Finds properties in the given fragment.</summary>
        /// <param name="fragment">The fragment to search.</param>
        public void FindProperties(CodeFragment fragment)
        {
            CodeFragment child = fragment.FirstChild;
            CodeFragment next  = null;

            while (child != null)
            {
                next = child.NextChild;

                if (child.IsParent)
                {
                    if (child.GetType() == typeof(OperationFragment))
                    {
                        try{
                            // Is it private? Note that if it is, "private" is removed.
                            bool isPublic = !Modifiers.Check(child.FirstChild, "private");

                            // Grab the property name:
                            CodeFragment propName = child.FirstChild;

                            if (propName == null)
                            {
                                child.Error("This value must be followed by something.");
                            }

                            if (propName.GetType() != typeof(VariableFragment))
                            {
                                child.Error("Didn't recognise this as a property. Please note that all code you'd like to run immediately should be inside a function called Start, or in the constructor of a class.");
                            }

                            VariableFragment vfrag = ((VariableFragment)child.FirstChild);

                            // These are never local:
                            vfrag.AfterVar = false;

                            string Name = vfrag.Value;

                            if (vfrag.IsKeyword())
                            {
                                child.Error("Can't use " + Name + " as a property because it's a keyword.");
                            }

                            if (Fields.ContainsKey(Name))
                            {
                                child.Error(Name + " has been defined twice.");
                            }

                            CodeFragment defaultValue = null;

                            if (vfrag.NextChild == null)
                            {
                            }
                            else if (vfrag.NextChild != null && !Types.IsTypeOf(vfrag.NextChild, typeof(OperatorFragment)))
                            {
                                // No type OR default, or the block straight after isn't : or =
                                child.Error(Name + " is missing a type or default value.");
                            }
                            else
                            {
                                OperatorFragment opFrag = (OperatorFragment)vfrag.NextChild;

                                // It must be a set otherwise it's invalid.
                                if (opFrag.Value == null || opFrag.Value.GetType() != typeof(OperatorSet))
                                {
                                    child.Error("Invalid default value provided for '" + Name + "'.");
                                }

                                defaultValue = opFrag.NextChild;
                            }

                            DefineField(Name, vfrag, isPublic, defaultValue);

                            child.Remove();

                            if (defaultValue != null)
                            {
                                GetInit().CodeBlock.AddChild(child);
                            }
                        }catch (CompilationException e) {
                            if (e.LineNumber == -1 && child != null)
                            {
                                // Setup line number:
                                e.LineNumber = child.GetLineNumber();
                            }

                            // Rethrow:
                            throw e;
                        }
                    }
                    else
                    {
                        FindProperties(child);
                    }
                }

                child = next;
            }
        }
예제 #13
0
        /// <summary>Compiles an operation fragment into an executable operation. The fragment may contain multiple
        /// operators and some may even be the same so the furthest right takes priority; 1+2+3 becomes 1+(2+3).
        /// The compiled fragments are placed back into the same operation fragment. When it's complete, the operation
        /// will only contain one compiled fragment.</summary>
        /// <param name="fragment">The operation fragment to compile.</param>
        /// <param name="parentBlock">The method the operations are compiling into.</param>
        public static void CompileOperators(OperationFragment fragment, CompiledMethod parentBlock)
        {
            CodeFragment     child           = fragment.FirstChild;
            OperatorFragment highestPriority = null;

            while (child != null)
            {
                if (child.GetType() == typeof(OperatorFragment))
                {
                    OperatorFragment thisOperator = (OperatorFragment)child;

                    // <= below enforces furthest right:
                    if (highestPriority == null || highestPriority.Value.Priority <= thisOperator.Value.Priority)
                    {
                        highestPriority = thisOperator;
                    }
                }

                child = child.NextChild;
            }

            if (highestPriority == null)
            {
                return;
            }

            CodeFragment left      = highestPriority.PreviousChild;
            CodeFragment right     = highestPriority.NextChild;
            CodeFragment leftUsed  = left;
            CodeFragment rightUsed = right;

            if (left == null || left.GetType() == typeof(OperatorFragment))
            {
                leftUsed = null;
            }
            else if (!Types.IsCompiled(left))
            {
                leftUsed = left.Compile(parentBlock);
            }

            if (right == null || right.GetType() == typeof(OperatorFragment))
            {
                rightUsed = null;
            }
            else if (!Types.IsCompiled(right))
            {
                rightUsed = right.Compile(parentBlock);
            }

            Operation newFragment = highestPriority.Value.ToOperation((CompiledFragment)leftUsed, (CompiledFragment)rightUsed, parentBlock);

            if (newFragment == null)
            {
                highestPriority.Error("Error: An operator has been used but with nothing to use it on! (It was a '" + highestPriority.Value.Pattern + "')");
            }

            // Replace out Left, Right and the operator itself with the new fragment:
            highestPriority.Remove();

            if (left == null)
            {
                newFragment.AddBefore(right);
            }
            else
            {
                newFragment.AddAfter(left);
            }

            if (rightUsed != null)
            {
                right.Remove();
            }

            if (leftUsed != null)
            {
                left.Remove();
            }

            // And call again to collect the rest:
            CompileOperators(fragment, parentBlock);
        }
		/// <summary>Adds this code fragment as a child before the given one.</summary>
		/// <param name="frag">The fragment to add this before.</param>
		public void AddBefore(CodeFragment frag){
			AddAfter(frag);
			frag.Remove();
			frag.AddAfter(this);
		}