Beispiel #1
0
        /// <summary>
        /// Generates the code for a CompoundStatement node.
        /// </summary>
        /// <param name="cs">The CompoundStatement node.</param>
        /// <returns>String containing C# code for CompoundStatement cs.</returns>
        private void GenerateCompoundStatement(SYMBOL previousSymbol, CompoundStatement cs, StringBuilder sb)
        {
            // opening brace
            GenerateIndentedLine("{", sb);
            m_braceCount++;

            if (m_insertCoopTerminationChecks)
            {
                // We have to check in event functions as well because the user can manually call these.
                if (previousSymbol is GlobalFunctionDefinition ||
                    previousSymbol is WhileStatement ||
                    previousSymbol is DoWhileStatement ||
                    previousSymbol is ForLoop ||
                    previousSymbol is StateEvent)
                {
                    GenerateIndentedLine(m_coopTerminationCheck, sb);
                }
            }

            foreach (SYMBOL kid in cs.kids)
            {
                GenerateNodeToSB(cs, kid, sb);
            }

            // closing brace
            m_braceCount--;
            GenerateIndentedLine("}", sb);
        }
Beispiel #2
0
        public void OnError(SYMBOL sy)
        {
            switch (sy)
            {
            case SYMBOL.CASE: OnError(15); break;

            case SYMBOL.WHILE: OnError(17); break;

            case SYMBOL.RETURN: OnError(52); break;

            //---------------------------------------------------------------------
            case SYMBOL.SEMI: OnError(14); break;

            case SYMBOL.COLON: OnError(5); break;

            case SYMBOL.LP: OnError(9); break;

            case SYMBOL.RP: OnError(4); break;

            case SYMBOL.RB: OnError(12); break;

            case SYMBOL.LC: OnError(8); break;

            case SYMBOL.RC: OnError(13); break;

            case SYMBOL.IN: OnError(62); break;

            case SYMBOL.identsy: OnError(2); break;

            default:
                throw new CompilingException(string.Format("Error: unknown symbol:{0} expected", sy), pos);
            }
        }
Beispiel #3
0
        /// <summary>
        ///     Replaces an instance of the node at s.kids[didx] with an assignment
        ///     node. The assignment node has the Declaration node on the left hand
        ///     side and a default initializer on the right hand side.
        /// </summary>
        /// <param name="s">
        ///     The node containing the Declaration node that needs replacing.
        /// </param>
        /// <param name="didx">Index of the Declaration node to replace.</param>
        private void AddImplicitInitialization(SYMBOL s, int didx)
        {
            // We take the kids for a while to play with them.
            int sKidSize = s.kids.Count;

            object[] sKids = new object[sKidSize];
            for (int i = 0; i < sKidSize; i++)
            {
                sKids[i] = s.kids.Pop();
            }

            // The child to be changed.
            Declaration currentDeclaration = (Declaration)sKids[didx];

            // We need an assignment node.
            Assignment newAssignment = new Assignment(currentDeclaration.yyps,
                                                      currentDeclaration,
                                                      GetZeroConstant(currentDeclaration.yyps,
                                                                      currentDeclaration.Datatype),
                                                      "=");

            sKids[didx] = newAssignment;

            // Put the kids back where they belong.
            for (int i = 0; i < sKidSize; i++)
            {
                s.kids.Add(sKids[i]);
            }
        }
Beispiel #4
0
        public void FindMark(SYMBOL smb, string mark, out string kind, out string form)
        {
            CogniPy.CNL.EN.InvTransform trans = new InvTransform(mark);
            trans.Convert(smb as CogniPy.CNL.EN.paragraph);
            var ckind = trans.GetMarkerKind();
            var cform = trans.GetMarkerForm();

            switch (ckind)
            {
            case InvTransform.EntityKind.Concept:
                kind = "concept"; break;

            case InvTransform.EntityKind.AnyRole:
                kind = "role"; break;

            case InvTransform.EntityKind.DataRole:
                kind = "datarole"; break;

            case InvTransform.EntityKind.DataType:
                kind = "datatype"; break;

            case InvTransform.EntityKind.Instance:
                kind = "instance"; break;

            default:
                throw new InvalidOperationException();
            }
            form = cform == endict.WordKind.NormalForm ? "NormalForm" : (cform == endict.WordKind.PastParticiple ? "PastParticiple" : (cform == endict.WordKind.SimplePast ? "SimplePast" : (cform == endict.WordKind.PluralFormNoun ? "PluralFormNoun" : "PluralFormVerb")));
        }
Beispiel #5
0
        /// <summary>
        /// Recursively called to transform each type of node. Will transform this
        /// node, then all of its children
        /// </summary>
        /// <param name="s">The current node to transform</param>
        private void TransformNode(SYMBOL s)
        {
            // make sure to put type lower in the inheritance hierarchy first
            // ie: since IdentConstant and StringConstant inherit from Constant,
            // put IdentConstant and StringConstant before Constant
            if (s is Declaration)
            {
                ((Declaration)s).Datatype = m_datatypeLSL2CS[((Declaration)s).Datatype];
            }
            else if (s is Constant)
            {
                ((Constant)s).Type = m_datatypeLSL2CS[((Constant)s).Type];
            }
            else if (s is TypecastExpression)
            {
                ((TypecastExpression)s).TypecastType = m_datatypeLSL2CS[((TypecastExpression)s).TypecastType];
            }
            else if (s is GlobalFunctionDefinition && "void" != ((GlobalFunctionDefinition)s).ReturnType) // we don't need to translate "void"
            {
                ((GlobalFunctionDefinition)s).ReturnType = m_datatypeLSL2CS[((GlobalFunctionDefinition)s).ReturnType];
            }

            for (int i = 0; i < s.kids.Count; i++)
            {
                if (!(s is Assignment || s is ArgumentDeclarationList) && s.kids[i] is Declaration)
                {
                    AddImplicitInitialization(s, i);
                }

                TransformNode((SYMBOL)s.kids[i]);
            }
        }
        /// <summary>
        /// Recursively called to transform each type of node. Will transform this
        /// node, then all it's children.
        /// </summary>
        /// <param name="s">The current node to transform.</param>
        private void TransformNode(SYMBOL s, Dictionary <string, string> GlobalMethods, Dictionary <string, ObjectList> MethodArguements)
        {
            // make sure to put type lower in the inheritance hierarchy first
            // ie: since IdentConstant and StringConstant inherit from Constant,
            // put IdentConstant and StringConstant before Constant
            if (s is Declaration)
            {
                ((Declaration)s).Datatype = m_datatypeLSL2OpenSim[((Declaration)s).Datatype];
            }
            else if (s is Constant)
            {
                ((Constant)s).Type = m_datatypeLSL2OpenSim[((Constant)s).Type];
            }
            else if (s is TypecastExpression)
            {
                ((TypecastExpression)s).TypecastType = m_datatypeLSL2OpenSim[((TypecastExpression)s).TypecastType];
            }
            else if (s is GlobalFunctionDefinition)
            {
                if ("void" == ((GlobalFunctionDefinition)s).ReturnType) // we don't need to translate "void"
                {
                    if (GlobalMethods != null && !GlobalMethods.ContainsKey(((GlobalFunctionDefinition)s).Name))
                    {
                        GlobalMethods.Add(((GlobalFunctionDefinition)s).Name, "void");
                    }
                }
                else
                {
                    ((GlobalFunctionDefinition)s).ReturnType = m_datatypeLSL2OpenSim[((GlobalFunctionDefinition)s).ReturnType];
                    if (GlobalMethods != null && !GlobalMethods.ContainsKey(((GlobalFunctionDefinition)s).Name))
                    {
                        GlobalMethods.Add(((GlobalFunctionDefinition)s).Name, ((GlobalFunctionDefinition)s).ReturnType);
                        MethodArguements.Add(((GlobalFunctionDefinition)s).Name, ((GlobalFunctionDefinition)s).kids);
                    }
                }
            }

            for (int i = 0; i < s.kids.Count; i++)
            {
                // It's possible that a child is null, for instance when the
                // assignment part in a for-loop is left out, ie:
                //
                //     for (; i < 10; i++)
                //     {
                //         ...
                //     }
                //
                // We need to check for that here.

                if (null != s.kids[i])
                {
                    if (!(s is Assignment || s is ArgumentDeclarationList) && s.kids[i] is Declaration)
                    {
                        AddImplicitInitialization(s, i);
                    }

                    TransformNode((SYMBOL)s.kids[i], null, null);
                }
            }
        }
        public static string getString(SYMBOL s)
        {
            switch (s)
            {
            case SYMBOL.CROSS:
                return("\u2715");

            case SYMBOL.ANCHOR:
                return("\u2693");

            case SYMBOL.LIGHTNING:
                return("\u21AF");

            case SYMBOL.FLAG:
                return("\u2691");

            case SYMBOL.PENCIL:
                return("\u270E");

            case SYMBOL.PLUS:
                return("\u002B");

            case SYMBOL.DELTA:
                return("\u0394");

            case SYMBOL.ARROW_UP_DOWN:
                return("\u21C5");

            case SYMBOL.CHECK:
                return("\u2713");

            case SYMBOL.SUN:
                return("\u2600");

            case SYMBOL.HEART:
                return("\u2665");

            case SYMBOL.DANGER:
                return("\u26A0");

            case SYMBOL.ARROW_RIGHT:
                return("\u2023");

            case SYMBOL.ARROW_UP:
                return("\u2191");

            case SYMBOL.ARROW_DOWN:
                return("\u2193");

            case SYMBOL.MERGE:
                return("\u26D5");

            case SYMBOL.ARROW_RIGHT_2:
                return("\u21A6");

            case SYMBOL.TRIANGLE_RIGHT:
                return("\u22B3");
            }
            return(null);
        }
Beispiel #8
0
 /// <summary>
 /// Prints text correctly indented, followed by a newline.
 /// </summary>
 /// <param name="s">String of text to print.</param>
 /// <param name="sym">Symbol being generated to extract original line
 /// number and column from.</param>
 /// <returns>Properly indented string s followed by newline.</returns>
 private void GenerateIndentedLine(string s, SYMBOL sym, StringBuilder sb)
 {
     GenerateIndented(s, sym, sb);
     sb.Append("\n");
     m_CSharpLine++;
     m_CSharpCol = 1;
 }
Beispiel #9
0
 /// <summary>
 /// Resets various counters and metadata.
 /// </summary>
 private void ResetCounters()
 {
     m_braceCount  = 0;
     m_CSharpLine  = 0;
     m_CSharpCol   = 1;
     m_positionMap = new Dictionary <KeyValuePair <int, int>, KeyValuePair <int, int> >();
     m_astRoot     = null;
 }
Beispiel #10
0
        /// <summary>
        /// Prints text correctly indented, followed by a newline.
        /// </summary>
        /// <param name="s">String of text to print.</param>
        /// <param name="sym">Symbol being generated to extract original line
        /// number and column from.</param>
        /// <returns>Properly indented string s followed by newline.</returns>
        private string GenerateIndentedLine(string s, SYMBOL sym)
        {
            string retstr = GenerateIndented(s, sym) + "\n";

            m_CSharpLine++;
            m_CSharpCol = 1;

            return(retstr);
        }
Beispiel #11
0
        /// <summary>
        /// Prints text.
        /// </summary>
        /// <param name="s">String of text to print.</param>
        /// <param name="sym">Symbol being generated to extract original line
        /// number and column from.</param>
        /// <returns>String s.</returns>
        private void Generate(string s, SYMBOL sym, StringBuilder sb)
        {
            sb.Append(s);
            if (null != sym)
            {
                m_positionMap.Add(new KeyValuePair <int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair <int, int>(sym.Line, sym.Position));
            }

            m_CSharpCol += s.Length;
        }
Beispiel #12
0
 public void Clear()
 {
     m_astRoot.kids = null;
     m_astRoot.yylx = null;
     m_astRoot.yyps = null;
     m_astRoot      = null;
     m_positionMap  = null;
     m_warnings.Clear();
     m_comms = null;
 }
Beispiel #13
0
        public override SYMBOL Action(Parser yyp)
        {
            SYMBOL yysym = base.Action(yyp);
            object obj   = yyp.m_symbols.Action(yyp, yysym, this.m_action);

            if (obj != null)
            {
                yysym.m_dollar = obj;
            }
            return(yysym);
        }
Beispiel #14
0
        /// <summary>
        /// Prints text.
        /// </summary>
        /// <param name="s">String of text to print.</param>
        /// <param name="sym">Symbol being generated to extract original line
        /// number and column from.</param>
        /// <returns>String s.</returns>
        private string Generate(string s, SYMBOL sym)
        {
            if (null != sym)
            {
                m_positionMap.Add(new KeyValuePair <int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair <int, int>(sym.Line, sym.Position));
            }

            m_CSharpCol += s.Length;

            return(s);
        }
Beispiel #15
0
 /// <summary>
 /// Attempt to recognize the given phonological environment string
 /// </summary>
 /// <param name="sEnvironment">phonological environment to recognize</param>
 /// <returns>true if environment is recognized; false otherwise</returns>
 public bool Recognize(string sEnvironment)
 {
     m_fSuccess = false;             // Start distrustful.
     try
     {
         InitParser(sEnvironment, m_saNaturalClasses, m_saSegments);
         SYMBOL ast = m_parser.Parse(sEnvironment);
         if (m_parser.Success)
         {
             m_fSuccess = true;
         }
         else
         {
             m_sErrorMessage = m_parser.ErrorMessage;
         }
     }
     catch (CSToolsException exc)
     {
         StringBuilder sb = new StringBuilder();
         if (m_parser.ErrorMessage == null)
         {
             sb.Append("<phonEnv status=\"syntax\" pos=\"");
             if (m_parser.Position != -1)
             {
                 sb.Append(m_parser.Position.ToString());
             }
             else
             {
                 sb.Append(exc.nChar.ToString());
             }
             sb.Append("\" syntaxErrType=\"");
             sb.Append(m_parser.SyntaxErrorType.ToString());
             sb.Append("\">");
             // Fix the string to be safe for XML.
             if (sEnvironment != null && sEnvironment != "")
             {
                 sEnvironment = sEnvironment.Replace("&", "&amp;");
                 sEnvironment = sEnvironment.Replace("<", "&lt;");
                 sEnvironment = sEnvironment.Replace(">", "&gt;");
             }
             sb.Append(sEnvironment);
             sb.Append("</phonEnv>");
         }
         else
         {
             sb.Append(m_parser.ErrorMessage);
         }
         m_sErrorMessage  = sb.ToString();
         m_parser.Success = false;
     }
     return(m_fSuccess);
 }
Beispiel #16
0
        /// <summary>
        /// Generates the code for a Statement node.
        /// </summary>
        /// <param name="s">The Statement node.</param>
        /// <returns>String containing C# code for Statement s.</returns>
        private void GenerateStatement(SYMBOL previousSymbol, Statement s, StringBuilder sb)
        {
            string retstr           = String.Empty;
            bool   printSemicolon   = true;
            bool   transformToBlock = false;

            if (m_insertCoopTerminationChecks)
            {
                // A non-braced single line do while structure cannot contain multiple statements.
                // So to insert the termination check we change this to a braced control structure instead.
                if (previousSymbol is WhileStatement ||
                    previousSymbol is DoWhileStatement ||
                    previousSymbol is ForLoop)
                {
                    transformToBlock = true;

                    // FIXME: This will be wrongly indented because the previous for/while/dowhile will have already indented.
                    GenerateIndentedLine("{", sb);

                    GenerateIndentedLine(m_coopTerminationCheck, sb);
                }
            }

            Indent(sb);

            if (0 < s.kids.Count)
            {
                // Jump label prints its own colon, we don't need a semicolon.
                printSemicolon = !(s.kids.Top is JumpLabel);

                // If we encounter a lone Ident, we skip it, since that's a C#
                // (MONO) error.
                if (!(s.kids.Top is IdentExpression && 1 == s.kids.Count))
                {
                    foreach (SYMBOL kid in s.kids)
                    {
                        GenerateNodeToSB(s, kid, sb);
                    }
                }
            }

            if (printSemicolon)
            {
                GenerateLine(";", sb);
            }

            if (transformToBlock)
            {
                // FIXME: This will be wrongly indented because the for/while/dowhile is currently handling the unindent
                GenerateIndentedLine("}", sb);
            }
        }
Beispiel #17
0
        /// <summary>
        /// Prints text correctly indented.
        /// </summary>
        /// <param name="s">String of text to print.</param>
        /// <param name="sym">Symbol being generated to extract original line
        /// number and column from.</param>
        /// <returns>Properly indented string s.</returns>
        private string GenerateIndented(string s, SYMBOL sym)
        {
            string retstr = Indent() + s;

            if (null != sym)
            {
                m_positionMap.Add(new KeyValuePair <int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair <int, int>(sym.Line, sym.Position));
            }

            m_CSharpCol += s.Length;

            return(retstr);
        }
Beispiel #18
0
 private bool expect(SYMBOL sy)
 {
     if (lex.sy == sy)
     {
         lex.InSymbol();
         return(true);
     }
     else
     {
         error.OnError(sy); // add code throw a exception
         return(false);
     }
 }
        /// <summary>
        /// Recursively called to transform each type of node. Will transform this
        /// node, then all it's children.
        /// </summary>
        /// <param name="s">The current node to transform.</param>
        private void TransformNode(SYMBOL s)
        {
//            m_log.DebugFormat("[LSL2CSCODETRANSFORMER]: Tranforming node {0}", s);

            // make sure to put type lower in the inheritance hierarchy first
            // ie: since IdentConstant and StringConstant inherit from Constant,
            // put IdentConstant and StringConstant before Constant
            if (s is Declaration)
            {
                ((Declaration)s).Datatype = m_datatypeLSL2OpenSim[((Declaration)s).Datatype];
            }
            else if (s is Constant)
            {
                ((Constant)s).Type = m_datatypeLSL2OpenSim[((Constant)s).Type];
            }
            else if (s is TypecastExpression)
            {
                ((TypecastExpression)s).TypecastType = m_datatypeLSL2OpenSim[((TypecastExpression)s).TypecastType];
            }
            else if (s is GlobalFunctionDefinition && "void" != ((GlobalFunctionDefinition)s).ReturnType)  // we don't need to translate "void"
            {
                ((GlobalFunctionDefinition)s).ReturnType = m_datatypeLSL2OpenSim[((GlobalFunctionDefinition)s).ReturnType];
            }

            for (int i = 0; i < s.kids.Count; i++)
            {
                // It's possible that a child is null, for instance when the
                // assignment part in a for-loop is left out, ie:
                //
                //     for (; i < 10; i++)
                //     {
                //         ...
                //     }
                //
                // We need to check for that here.
                if (null != s.kids[i])
                {
//                    m_log.Debug("[LSL2CSCODETRANSFORMER]: Moving down level");

                    if (!(s is Assignment || s is ArgumentDeclarationList) && s.kids[i] is Declaration)
                    {
                        AddImplicitInitialization(s, i);
                    }

                    TransformNode((SYMBOL)s.kids[i]);

//                    m_log.Debug("[LSL2CSCODETRANSFORMER]: Moving up level");
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// Pass the new CodeTranformer an abstract syntax tree.
        /// </summary>
        /// <param name="astRoot">The root node of the AST.</param>
        public LSL2CSCodeTransformer(SYMBOL astRoot)
        {
            m_astRoot = astRoot;

            m_datatypeLSL2CS = new Dictionary <string, string>()
            {
                { "integer", "lsl_integer" },
                { "float", "lsl_float" },
                { "key", "lsl_string" },
                { "string", "lsl_string" },
                { "vector", "lsl_vector" },
                { "rotation", "lsl_rotation" },
                { "list", "lsl_list" }
            };
        }
    public static void printThisTree(SYMBOL ast)
    {
        for (int i = 0; i < m_indent; i++)
        {
            Console.Write("  ");
        }
        Console.WriteLine(ast.ToString());

        m_indent++;
        foreach (SYMBOL s in ast.kids)
        {
            printThisTree(s);
        }
        m_indent--;
    }
Beispiel #22
0
        /// <summary>
        /// Generates the code for a ForLoopStatement node.
        /// </summary>
        /// <param name="fls">The ForLoopStatement node.</param>
        /// <returns>String containing C# code for ForLoopStatement fls.</returns>
        private string GenerateForLoopStatement(ForLoopStatement fls)
        {
            string retstr = String.Empty;

            int comma = fls.kids.Count - 1;  // tells us whether to print a comma

            // It's possible that all we have is an empty Ident, for example:
            //
            //     for (x; x < 10; x++) { ... }
            //
            // Which is illegal in C# (MONO). We'll skip it.
            if (fls.kids.Top is IdentExpression && 1 == fls.kids.Count)
            {
                return(retstr);
            }

            for (int i = 0; i < fls.kids.Count; i++)
            {
                SYMBOL s = (SYMBOL)fls.kids[i];

                // Statements surrounded by parentheses in for loops
                //
                // e.g.  for ((i = 0), (j = 7); (i < 10); (++i))
                //
                // are legal in LSL but not in C# so we need to discard the parentheses
                //
                // The following, however, does not appear to be legal in LLS
                //
                // for ((i = 0, j = 7); (i < 10); (++i))
                //
                // As of Friday 20th November 2009, the Linden Lab simulators appear simply never to compile or run this
                // script but with no debug or warnings at all!  Therefore, we won't deal with this yet (which looks
                // like it would be considerably more complicated to handle).
                while (s is ParenthesisExpression)
                {
                    s = (SYMBOL)s.kids.Pop();
                }

                retstr += GenerateNode(s);
                if (0 < comma--)
                {
                    retstr += Generate(", ");
                }
            }

            return(retstr);
        }
        /// <summary>
        /// Pass the new CodeTranformer an abstract syntax tree.
        /// </summary>
        /// <param name="astRoot">The root node of the AST.</param>
        public LSL2CSCodeTransformer(SYMBOL astRoot)
        {
            m_astRoot = astRoot;

            // let's populate the dictionary
            if (null == m_datatypeLSL2OpenSim)
            {
                m_datatypeLSL2OpenSim = new Dictionary <string, string>();
                m_datatypeLSL2OpenSim.Add("integer", "LSL_Types.LSLInteger");
                m_datatypeLSL2OpenSim.Add("float", "LSL_Types.LSLFloat");
                m_datatypeLSL2OpenSim.Add("key", "LSL_Types.LSLString");
                m_datatypeLSL2OpenSim.Add("string", "LSL_Types.LSLString");
                m_datatypeLSL2OpenSim.Add("vector", "LSL_Types.Vector3");
                m_datatypeLSL2OpenSim.Add("rotation", "LSL_Types.Quaternion");
                m_datatypeLSL2OpenSim.Add("list", "LSL_Types.list");
            }
        }
Beispiel #24
0
        /// <summary>
        /// Generates the code for an identifier
        /// </summary>
        /// <param name="id">The symbol name</param>
        /// <param name="s">The Symbol node.</param>
        /// <returns>String containing C# code for identifier reference.</returns>
        private void GenerateIdentifier(string id, SYMBOL s, StringBuilder sb)
        {
            if (m_comms != null)
            {
                object value = m_comms.LookupModConstant(id);
                if (value != null)
                {
                    string retval = null;
                    if (value is int)
                    {
                        retval = String.Format("new LSL_Types.LSLInteger({0})", ((int)value).ToString());
                    }
                    else if (value is float)
                    {
                        retval = String.Format("new LSL_Types.LSLFloat({0})", ((float)value).ToString());
                    }
                    else if (value is string)
                    {
                        retval = String.Format("new LSL_Types.LSLString(\"{0}\")", ((string)value));
                    }
                    else if (value is OpenMetaverse.UUID)
                    {
                        retval = String.Format("new LSL_Types.key(\"{0}\")", ((OpenMetaverse.UUID)value).ToString());
                    }
                    else if (value is OpenMetaverse.Vector3)
                    {
                        retval = String.Format("new LSL_Types.Vector3(\"{0}\")", ((OpenMetaverse.Vector3)value).ToString());
                    }
                    else if (value is OpenMetaverse.Quaternion)
                    {
                        retval = String.Format("new LSL_Types.Quaternion(\"{0}\")", ((OpenMetaverse.Quaternion)value).ToString());
                    }
                    else
                    {
                        retval = id;
                    }

                    Generate(retval, s, sb);
                    return;
                }
            }

            Generate(CheckName(id), s, sb);
            return;
        }
    public static void Main(string[] argv)
    {
        StreamReader s      = new StreamReader(argv[0]);
        string       source = s.ReadToEnd();

        CSCodeGenerator cscg   = new CSCodeGenerator();
        string          output = cscg.Convert(source);

        if (1 < argv.Length && "-t" == argv[1])
        {
            Parser p = new LSLSyntax();
            LSL2CSCodeTransformer codeTransformer = new LSL2CSCodeTransformer(p.Parse(source));
            SYMBOL ast = codeTransformer.Transform();
            printThisTree(ast);
        }
        else
        {
            Console.Write(output);
        }
    }
        /// <summary>
        ///     Pass the new CodeTransformer an abstract syntax tree.
        /// </summary>
        /// <param name="astRoot">The root node of the AST.</param>
        /// <param name="originalScript">The original script that we are converting</param>
        public LSL2CSCodeTransformer(SYMBOL astRoot, string originalScript)
        {
            m_astRoot        = astRoot;
            m_originalScript = originalScript;

            // let's populate the dictionary
            if (null == m_datatypeLSL2OpenSim)
            {
                m_datatypeLSL2OpenSim = new Dictionary <string, string>
                {
                    { "integer", "LSL_Types.LSLInteger" },
                    { "float", "LSL_Types.LSLFloat" },
                    { "key", "LSL_Types.LSLString" },
                    { "string", "LSL_Types.LSLString" },
                    { "vector", "LSL_Types.Vector3" },
                    { "rotation", "LSL_Types.Quaternion" },
                    { "list", "LSL_Types.list" }
                };
            }
        }
Beispiel #27
0
        // This code checks for LSL of the following forms, and generates a
        // warning if it finds them.
        //
        // list l = [ "foo" ];
        // l = (l=[]) + l + ["bar"];
        // (produces l=["foo","bar"] in SL but l=["bar"] in C#)
        //
        // integer i;
        // integer j;
        // i = (j = 3) + (j = 4) + (j = 5);
        // (produces j=3 in SL but j=5 in C#)
        //
        // Without this check, that code passes compilation, but does not do what
        // the end user expects, because LSL in SL evaluates right to left instead
        // of left to right.
        //
        // The theory here is that producing an error and alerting the end user that
        // something needs to change is better than silently generating incorrect code.
        private void checkForMultipleAssignments(List <string> identifiers, SYMBOL s)
        {
            if (s is Assignment)
            {
                Assignment a        = (Assignment)s;
                string     newident = null;

                if (a.kids[0] is Declaration)
                {
                    newident = ((Declaration)a.kids[0]).Id;
                }
                else if (a.kids[0] is IDENT)
                {
                    newident = ((IDENT)a.kids[0]).yytext;
                }
                else if (a.kids[0] is IdentDotExpression)
                {
                    newident = ((IdentDotExpression)a.kids[0]).Name; // +"." + ((IdentDotExpression)a.kids[0]).Member;
                }
                else
                {
                    AddWarning(String.Format("Multiple assignments checker internal error '{0}' at line {1} column {2}.",
                                             a.kids[0].GetType(), ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position));
                }

                if (identifiers.Contains(newident))
                {
                    AddWarning(String.Format("Multiple assignments to '{0}' at line {1} column {2}; results may differ between LSL and C#.",
                                             newident, ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position));
                }

                identifiers.Add(newident);
            }

            int index;

            for (index = 0; index < s.kids.Count; index++)
            {
                checkForMultipleAssignments(identifiers, (SYMBOL)s.kids[index]);
            }
        }
Beispiel #28
0
        bool s_exp24()
        {
            while (lex.sy == SYMBOL.RELOP || lex.sy == SYMBOL.IS || lex.sy == SYMBOL.IN || lex.sy == SYMBOL.AS)
            {
                SYMBOL  sy  = lex.sy;
                SYMBOL2 Opr = lex.opr;
                lex.InSymbol();
                switch (sy)
                {
                case SYMBOL.RELOP:
                    s_exp9();
                    switch (Opr)
                    {
                    case SYMBOL2.GTR: gen.emit(INSTYPE.GTR); break;

                    case SYMBOL2.LSS: gen.emit(INSTYPE.LSS); break;

                    case SYMBOL2.LEQ: gen.emit(INSTYPE.LEQ); break;

                    case SYMBOL2.GEQ: gen.emit(INSTYPE.GEQ); break;
                    }
                    break;

                case SYMBOL.IN:
                    s_exp9();
                    gen.emit(INSTYPE.LSS);
                    break;

                case SYMBOL.IS:
                    s_var(true);
                    s_call(Constant.FUNC_IS_TYPE, 2);
                    break;

                case SYMBOL.AS:
                    s_var(true);
                    s_call(Constant.FUNC_CAST_VALUE_TYPE, 2);
                    break;
                }
            }
            return(true);
        }
Beispiel #29
0
        public Numeric(SYMBOL sy, Sym sym)
        {
            switch (sy)
            {
            case SYMBOL.intcon:
                ty    = NUMTYPE.intcon;
                value = sym.inum;
                break;

            case SYMBOL.floatcon:
                ty    = NUMTYPE.doublecon;
                value = sym.fnum;
                break;

            case SYMBOL.stringcon:
                ty    = NUMTYPE.stringcon;
                value = sym.stab;
                break;

            case SYMBOL.nullsy:
                ty    = NUMTYPE.nullcon;
                value = null;
                break;

            case SYMBOL.VOID:
                ty    = NUMTYPE.voidcon;
                value = null;
                break;

            case SYMBOL.truesy:
                ty    = NUMTYPE.boolcon;
                value = true;
                break;

            case SYMBOL.falsesy:
                ty    = NUMTYPE.boolcon;
                value = false;
                break;
            }
        }
Beispiel #30
0
        /// <summary>
        ///     Recursively called to transform each type of node. Will transform this
        ///     node, then all it's children.
        /// </summary>
        /// <param name="s">The current node to transform.</param>
        /// <param name="GlobalMethods"> </param>
        /// <param name="MethodArguements"> </param>
        /// <param name="scopesParent"> </param>
        /// <param name="scopeCurrent"> </param>
        private void TransformNode(SYMBOL s, Dictionary <string, string> GlobalMethods,
                                   Dictionary <string, ObjectList> MethodArguements, List <int> scopesParent,
                                   int scopeCurrent)
        {
            // make sure to put type lower in the inheritance hierarchy first
            // ie: since IdentConstant and StringConstant inherit from Constant,
            // put IdentConstant and StringConstant before Constant
            if (s is Declaration)
            {
                Declaration dec = (Declaration)s;
                dec.Datatype = m_datatypeLSL2OpenSim[dec.Datatype];
            }
            else if (s is Constant)
            {
                ((Constant)s).Type = m_datatypeLSL2OpenSim[((Constant)s).Type];
            }
            else if (s is TypecastExpression)
            {
                ((TypecastExpression)s).TypecastType = m_datatypeLSL2OpenSim[((TypecastExpression)s).TypecastType];
            }
            else if (s is GlobalFunctionDefinition)
            {
                GlobalFunctionDefinition fun = (GlobalFunctionDefinition)s;
                if ("void" == fun.ReturnType) // we don't need to translate "void"
                {
                    if (GlobalMethods != null && !GlobalMethods.ContainsKey(fun.Name))
                    {
                        GlobalMethods.Add(fun.Name, "void");
                    }
                }
                else
                {
                    fun.ReturnType =
                        m_datatypeLSL2OpenSim[fun.ReturnType];
                    if (GlobalMethods != null && !GlobalMethods.ContainsKey(fun.Name))
                    {
                        GlobalMethods.Add(fun.Name, fun.ReturnType);
                        MethodArguements.Add(fun.Name, (s).kids);
                    }
                }
                //Reset the variables, we changed events
                m_currentEvent = fun.Name;
                m_localVariableValues.Add("global_function_" + fun.Name, new Dictionary <string, SYMBOL>());
                m_localVariableValuesStr.Add("global_function_" + fun.Name, new Dictionary <string, string>());
                m_duplicatedLocalVariableValues.Add("global_function_" + fun.Name, new Dictionary <string, SYMBOL>());
                m_localVariableScope.Add("global_function_" + fun.Name, new Dictionary <string, int>());
                // this is a new function, lets clear the parent scopes and set the current scope to this
                scopesParent.Clear();
                scopeCurrent = s.pos;
                scopesParent.Add(scopeCurrent);
            }
            else if (s is State)
            {
                //Reset the variables, we changed events
                State evt = (State)s;
                m_currentState = evt.Name;
            }
            else if (s is StateEvent)
            {
                //Reset the variables, we changed events
                StateEvent evt = (StateEvent)s;
                m_currentEvent = evt.Name;
                m_localVariableValues.Add(m_currentState + "_" + evt.Name, new Dictionary <string, SYMBOL>());
                m_localVariableValuesStr.Add(m_currentState + "_" + evt.Name, new Dictionary <string, string>());
                m_duplicatedLocalVariableValues.Add(m_currentState + "_" + evt.Name, new Dictionary <string, SYMBOL>());
                m_localVariableScope.Add(m_currentState + "_" + evt.Name, new Dictionary <string, int>());
                // this is a new state event, lets clear the parent scopes and set the current scope to this
                scopesParent.Clear();
                scopeCurrent = s.pos;
                scopesParent.Add(scopeCurrent);
            }
            else if (s is ArgumentDeclarationList)
            {
                ArgumentDeclarationList adl = (ArgumentDeclarationList)s;
                foreach (SYMBOL child in adl.kids)
                {
                    Declaration d = child as Declaration;
                    if (d != null)
                    {
                        m_duplicatedLocalVariableValues[GetLocalVariableDictionaryKey()][d.Id] = null;
                    }
                }
                //m_duplicatedLocalVariableValues.Add(m_currentState + "_" + evt.Name, new Dictionary<string, SYMBOL>());
            }
            else if (s is GlobalVariableDeclaration)
            {
                GlobalVariableDeclaration gvd = (GlobalVariableDeclaration)s;
                foreach (SYMBOL child in gvd.kids)
                {
                    if (child is Assignment)
                    {
                        bool   isDeclaration = false;
                        string decID         = "";
                        foreach (SYMBOL assignmentChild in child.kids)
                        {
                            if (assignmentChild is Declaration)
                            {
                                Declaration d = (Declaration)assignmentChild;
                                decID         = d.Id;
                                isDeclaration = true;
                            }
                            else if (assignmentChild is IdentExpression)
                            {
                                IdentExpression identEx = (IdentExpression)assignmentChild;
                                if (isDeclaration)
                                {
                                    if (m_globalVariableValues.ContainsKey(decID))
                                    {
                                        m_duplicatedGlobalVariableValues[decID] = identEx;
                                    }
                                    m_globalVariableValues[decID] = identEx.Name;
                                }
                            }
                            else if (assignmentChild is ListConstant)
                            {
                                ListConstant listConst = (ListConstant)assignmentChild;
                                foreach (SYMBOL listChild in listConst.kids)
                                {
                                    if (listChild is ArgumentList)
                                    {
                                        ArgumentList argList = (ArgumentList)listChild;
                                        int          i       = 0;
                                        bool         changed = false;
                                        object[]     p       = new object[argList.kids.Count];
                                        foreach (SYMBOL objChild in argList.kids)
                                        {
                                            p[i] = objChild;
                                            if (objChild is IdentExpression)
                                            {
                                                IdentExpression identEx = (IdentExpression)objChild;
                                                if (m_globalVariableValues.ContainsKey(identEx.Name))
                                                {
                                                    changed = true;
                                                    p[i]    = new IdentExpression(identEx.yyps,
                                                                                  m_globalVariableValues[identEx.Name])
                                                    {
                                                        pos      = objChild.pos,
                                                        m_dollar = objChild.m_dollar
                                                    };
                                                }
                                            }
                                            i++;
                                        }
                                        if (changed)
                                        {
                                            argList.kids = new ObjectList();
                                            foreach (object o in p)
                                            {
                                                argList.kids.Add(o);
                                            }
                                        }
                                        if (isDeclaration)
                                        {
                                            if (m_globalVariableValues.ContainsKey(decID))
                                            {
                                                m_duplicatedGlobalVariableValues[decID] = listConst;
                                            }
                                            m_globalVariableValues[decID] = listConst.Value;
                                        }
                                    }
                                }
                            }
                            else if (assignmentChild is VectorConstant || assignmentChild is RotationConstant)
                            {
                                Constant listConst = (Constant)assignmentChild;
                                int      i         = 0;
                                bool     changed   = false;
                                object[] p         = new object[listConst.kids.Count];
                                foreach (SYMBOL objChild in listConst.kids)
                                {
                                    p[i] = objChild;
                                    if (objChild is IdentExpression)
                                    {
                                        IdentExpression identEx = (IdentExpression)objChild;
                                        if (m_globalVariableValues.ContainsKey(identEx.Name))
                                        {
                                            changed = true;
                                            p[i]    = new IdentExpression(identEx.yyps,
                                                                          m_globalVariableValues[identEx.Name])
                                            {
                                                pos      = objChild.pos,
                                                m_dollar = objChild.m_dollar
                                            };
                                        }
                                    }
                                    i++;
                                }
                                if (changed)
                                {
                                    listConst.kids = new ObjectList();
                                    foreach (object o in p)
                                    {
                                        listConst.kids.Add(o);
                                    }
                                }
                                if (isDeclaration)
                                {
                                    if (m_globalVariableValues.ContainsKey(decID))
                                    {
                                        m_duplicatedGlobalVariableValues[decID] = listConst;
                                    }
                                    m_globalVariableValues[decID] = listConst.Value;
                                }
                            }
                            else if (assignmentChild is Constant)
                            {
                                Constant identEx = (Constant)assignmentChild;
                                if (isDeclaration)
                                {
                                    if (m_globalVariableValues.ContainsKey(decID))
                                    {
                                        m_duplicatedGlobalVariableValues[decID] = identEx;
                                    }
                                    m_globalVariableValues[decID] = identEx.Value;
                                }
                            }
                        }
                    }
                }
            }
            else if (s is Assignment && m_currentEvent != "")
            {
                Assignment ass           = (Assignment)s;
                bool       isDeclaration = false;
                string     decID         = "";
                foreach (SYMBOL assignmentChild in ass.kids)
                {
                    if (assignmentChild is Declaration)
                    {
                        Declaration d = (Declaration)assignmentChild;
                        decID         = d.Id;
                        isDeclaration = true;
                    }
                    else if (assignmentChild is IdentExpression)
                    {
                        IdentExpression identEx = (IdentExpression)assignmentChild;
                        if (isDeclaration)
                        {
                            if (m_localVariableValues[GetLocalVariableDictionaryKey()].ContainsKey(decID) &&
                                !m_duplicatedLocalVariableValues[GetLocalVariableDictionaryKey()].ContainsKey(decID) &&
                                scopesParent.Contains(m_localVariableScope[GetLocalVariableDictionaryKey()][decID]))
                            {
                                m_duplicatedLocalVariableValues[GetLocalVariableDictionaryKey()][decID] =
                                    m_localVariableValues[GetLocalVariableDictionaryKey()][decID];
                            }
                            m_localVariableValues[GetLocalVariableDictionaryKey()][decID]    = identEx;
                            m_localVariableValuesStr[GetLocalVariableDictionaryKey()][decID] = identEx.Name;
                            m_localVariableScope[GetLocalVariableDictionaryKey()][decID]     = scopeCurrent;
                        }
                    }
                    else if (assignmentChild is ListConstant)
                    {
                        ListConstant listConst = (ListConstant)assignmentChild;
                        foreach (SYMBOL listChild in listConst.kids)
                        {
                            if (listChild is ArgumentList)
                            {
                                ArgumentList argList = (ArgumentList)listChild;
                                int          i       = 0;
                                bool         changed = false;
                                object[]     p       = new object[argList.kids.Count];
                                foreach (SYMBOL objChild in argList.kids)
                                {
                                    p[i] = objChild;
                                    if (objChild is IdentExpression)
                                    {
                                        IdentExpression identEx = (IdentExpression)objChild;
                                        if (
                                            m_localVariableValues[GetLocalVariableDictionaryKey()].ContainsKey(
                                                identEx.Name))
                                        {
                                            changed = true;
                                            p[i]    = new IdentExpression(identEx.yyps,
                                                                          m_localVariableValuesStr[
                                                                              GetLocalVariableDictionaryKey()][identEx.Name
                                                                          ])
                                            {
                                                pos      = objChild.pos,
                                                m_dollar = objChild.m_dollar
                                            };
                                        }
                                    }
                                    i++;
                                }
                                if (changed)
                                {
                                    argList.kids = new ObjectList();
                                    foreach (object o in p)
                                    {
                                        argList.kids.Add(o);
                                    }
                                }
                                if (isDeclaration)
                                {
                                    if (m_localVariableValues[GetLocalVariableDictionaryKey()].ContainsKey(decID) &&
                                        !m_duplicatedLocalVariableValues[GetLocalVariableDictionaryKey()].ContainsKey(
                                            decID) &&
                                        scopesParent.Contains(
                                            m_localVariableScope[GetLocalVariableDictionaryKey()][decID]))
                                    {
                                        m_duplicatedLocalVariableValues[GetLocalVariableDictionaryKey()][decID] =
                                            m_localVariableValues[GetLocalVariableDictionaryKey()][decID];
                                    }
                                    m_localVariableValues[GetLocalVariableDictionaryKey()][decID]    = listConst;
                                    m_localVariableValuesStr[GetLocalVariableDictionaryKey()][decID] = listConst.Value;
                                    m_localVariableScope[GetLocalVariableDictionaryKey()][decID]     = scopeCurrent;
                                }
                            }
                        }
                    }
                    else if (assignmentChild is VectorConstant || assignmentChild is RotationConstant)
                    {
                        Constant listConst = (Constant)assignmentChild;
                        int      i         = 0;
                        bool     changed   = false;
                        object[] p         = new object[listConst.kids.Count];
                        foreach (SYMBOL objChild in listConst.kids)
                        {
                            p[i] = objChild;
                            if (objChild is IdentExpression)
                            {
                                IdentExpression identEx = (IdentExpression)objChild;
                                if (m_localVariableValues[GetLocalVariableDictionaryKey()].ContainsKey(identEx.Name))
                                {
                                    changed = true;
                                    p[i]    = new IdentExpression(identEx.yyps,
                                                                  m_localVariableValuesStr[GetLocalVariableDictionaryKey()]
                                                                  [identEx.Name])
                                    {
                                        pos      = objChild.pos,
                                        m_dollar = objChild.m_dollar
                                    };
                                }
                            }
                            i++;
                        }
                        if (changed)
                        {
                            listConst.kids = new ObjectList();
                            foreach (object o in p)
                            {
                                listConst.kids.Add(o);
                            }
                        }
                        if (isDeclaration)
                        {
                            if (m_localVariableValues[GetLocalVariableDictionaryKey()].ContainsKey(decID) &&
                                !m_duplicatedLocalVariableValues[GetLocalVariableDictionaryKey()].ContainsKey(decID) &&
                                scopesParent.Contains(m_localVariableScope[GetLocalVariableDictionaryKey()][decID]))
                            {
                                m_duplicatedLocalVariableValues[GetLocalVariableDictionaryKey()][decID] =
                                    m_localVariableValues[GetLocalVariableDictionaryKey()][decID];
                            }
                            m_localVariableValues[GetLocalVariableDictionaryKey()][decID]    = listConst;
                            m_localVariableValuesStr[GetLocalVariableDictionaryKey()][decID] = listConst.Value;
                            m_localVariableScope[GetLocalVariableDictionaryKey()][decID]     = scopeCurrent;
                        }
                    }
                    else if (assignmentChild is Constant)
                    {
                        Constant identEx = (Constant)assignmentChild;
                        if (isDeclaration)
                        {
                            if (m_localVariableValues[GetLocalVariableDictionaryKey()].ContainsKey(decID) &&
                                !m_duplicatedLocalVariableValues[GetLocalVariableDictionaryKey()].ContainsKey(decID) &&
                                scopesParent.Contains(m_localVariableScope[GetLocalVariableDictionaryKey()][decID]))
                            {
                                m_duplicatedLocalVariableValues[GetLocalVariableDictionaryKey()][decID] =
                                    m_localVariableValues[GetLocalVariableDictionaryKey()][decID];
                            }
                            m_localVariableValues[GetLocalVariableDictionaryKey()][decID]    = identEx;
                            m_localVariableValuesStr[GetLocalVariableDictionaryKey()][decID] = identEx.Value;
                            m_localVariableScope[GetLocalVariableDictionaryKey()][decID]     = scopeCurrent;
                        }
                    }
                }
            }

            /*if(s is Statement)
             * {
             *  if(s.kids.Count == 1 && s.kids[0] is Assignment)
             *  {
             *      Assignment assignment = (Assignment)s.kids[0];
             *      object[] p = new object[assignment.kids.Count];
             *      int i = 0;
             *      int toRemove = -1;
             *      foreach(SYMBOL assignmentChild in assignment.kids)
             *      {
             *          p[i] = assignmentChild;
             *          if(assignmentChild is Declaration)
             *          {
             *              Declaration d = (Declaration)assignmentChild;
             *              if(m_allVariableValues.Contains(d.Id))
             *                  toRemove = i;
             *              else
             *                  m_allVariableValues.Add(d.Id);
             *          }
             *          i++;
             *      }
             *      if(toRemove != -1)
             *      {
             *          List<object> ps = new List<object>();
             *          foreach(object obj in p)
             *              ps.Add(obj);
             *          ps[toRemove] = new IDENT(null)
             *          {
             *              kids = new ObjectList(),
             *              pos = ((SYMBOL)ps[toRemove]).pos,
             *              m_dollar = ((SYMBOL)ps[toRemove]).m_dollar,
             *              yylval = ((SYMBOL)ps[toRemove]).yylval,
             *              yylx = ((SYMBOL)ps[toRemove]).yylx,
             *              yyps = ((SYMBOL)ps[toRemove]).yyps,
             *              yytext = ps[toRemove] is Declaration ?
             *              ((Declaration)ps[toRemove]).Id
             *              : ((SYMBOL)ps[toRemove]).yyname,
             *          };
             *          ((SYMBOL)s.kids[0]).kids = new ObjectList();
             *          foreach(object obj in ps)
             *              if(obj != null)
             *                  ((SYMBOL)s.kids[0]).kids.Add(obj);
             *      }
             *  }
             * }*/

            for (int i = 0; i < s.kids.Count; i++)
            {
                // It's possible that a child is null, for instance when the
                // assignment part in a for-loop is left out, ie:
                //
                //     for (; i < 10; i++)
                //     {
                //         ...
                //     }
                //
                // We need to check for that here.

                if (null == s.kids[i])
                {
                    continue;
                }
                bool scopeAdded = false;
                // we need to keep track of the scope for dulicate variables
                if ((s is IfStatement) || (s is WhileStatement) || (s is ForLoopStatement) || (s is DoWhileStatement))
                {
                    scopeCurrent = ((SYMBOL)s.kids[i]).pos;
                    scopesParent.Add(scopeCurrent);
                    scopeAdded = true;
                }

                if (!(s is Assignment || s is ArgumentDeclarationList) && s.kids[i] is Declaration)
                {
                    AddImplicitInitialization(s, i);
                }

                TransformNode((SYMBOL)s.kids[i], null, null, scopesParent, scopeCurrent);

                // we need to remove the current scope from the parent since we are no longer in that scope
                if (scopeAdded)
                {
                    scopesParent.Remove(scopeCurrent);
                }
            }
        }
Beispiel #31
0
 public Token(SYMBOL sy, SYMBOL2 opr)
     : this()
 {
     this.sy = sy;
     this.opr = opr;
 }
Beispiel #32
0
        public SYMBOL ksy; // key work symbol

        #endregion Fields

        #region Constructors

        public JKey(string key, SYMBOL ksy)
        {
            this.key = key;
            this.ksy = ksy;
        }
Beispiel #33
0
        public void OnError(SYMBOL sy)
        {
            switch (sy)
            {
                case SYMBOL.CASE: OnError(15); break;
                case SYMBOL.WHILE: OnError(17); break;
                case SYMBOL.RETURN: OnError(52); break;

                //---------------------------------------------------------------------
                case SYMBOL.SEMI: OnError(14); break;
                case SYMBOL.COLON: OnError(5); break;
                case SYMBOL.LP: OnError(9); break;
                case SYMBOL.RP: OnError(4); break;
                case SYMBOL.RB: OnError(12); break;
                case SYMBOL.LC: OnError(8); break;
                case SYMBOL.RC: OnError(13); break;
                case SYMBOL.IN: OnError(62); break;
                case SYMBOL.identsy: OnError(2); break;

                default:
                    throw new CompilingException(string.Format("Error: unknown symbol:{0} expected", sy), pos);
            }
        }