Example #1
0
        private static ParseInfo Parse(byte[] buffer, int offset, int length)
        {
            // First Line
            HttpParser parser = new HttpParser(buffer, offset, length);
            string method;
            string uri;
            HttpVersion version;
            parser.Token(out method).Space().RequestUri(out uri).Space().Version(out version).CarriageReturnLineFeed();
            ParseInfo parseInfo = new ParseInfo
                                  {
                                      Length = length,
                                      Version = version,
                                      Method = method == null ? null : new HttpRequestMethod(method),
                                      Uri = uri,
                                  };
            if (!parser.Success)
                return parseInfo;

            int firstLineLength = parser.Offset - offset;

            // Header
            int? endHeaderOffset;
            HttpHeader header = new HttpHeader(GetHeaderFields(out endHeaderOffset, buffer, offset + firstLineLength, length - firstLineLength));
            parseInfo.Header = header;
            if (endHeaderOffset == null)
                return parseInfo;

            int headerLength = endHeaderOffset.Value - offset - firstLineLength;

            // Body
            Datagram body = ParseBody(buffer, offset + firstLineLength + headerLength, length - firstLineLength - headerLength, IsBodyPossible(header), header);
            parseInfo.Body = body;
            parseInfo.Length = firstLineLength + headerLength + body.Length;
            return parseInfo;
        }
Example #2
0
        private static ParseInfo Parse(byte[] buffer, int offset, int length)
        {
            // First Line
            HttpParser parser = new HttpParser(buffer, offset, length);
            HttpVersion version;
            uint? statusCode;
            Datagram reasonPhrase;
            parser.Version(out version).Space().DecimalNumber(3, out statusCode).Space().SkipSpaces().ReasonPhrase(out reasonPhrase).CarriageReturnLineFeed();
            ParseInfo parseInfo = new ParseInfo
                                  {
                                      Length = length,
                                      Version = version,
                                      StatusCode = statusCode,
                                      ReasonPhrase = reasonPhrase
                                  };
            if (!parser.Success)
                return parseInfo;

            int firstLineLength = parser.Offset - offset;

            // Header
            int? endHeaderOffset;
            HttpHeader header = new HttpHeader(GetHeaderFields(out endHeaderOffset, buffer, offset + firstLineLength, length - firstLineLength));
            parseInfo.Header = header;
            if (endHeaderOffset == null)
                return parseInfo;

            int headerLength = endHeaderOffset.Value - offset - firstLineLength;

            // Body
            Datagram body = ParseBody(buffer, offset + firstLineLength + headerLength, length - firstLineLength - headerLength, IsBodyPossible(statusCode.Value), header);
            parseInfo.Body = body;
            parseInfo.Length = firstLineLength + headerLength + body.Length;
            return parseInfo;
        }
Example #3
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            if (!Parser.Validate(state.Code, "if (", ref i) && !Parser.Validate(state.Code, "if(", ref i))
            {
                return(null);
            }

            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }

            var condition = (Expression)ExpressionTree.Parse(state, ref i);

            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }

            if (state.Code[i] != ')')
            {
                throw new ArgumentException("code (" + i + ")");
            }

            do
            {
                i++;
            }while (Tools.IsWhiteSpace(state.Code[i]));

            var combinedBody = state.Code[i] == '{';

            CodeNode body = Parser.Parse(state, ref i, 0);

            if (body is FunctionDefinition)
            {
                if (state.message != null)
                {
                    state.message(MessageLevel.CriticalWarning, body.Position, body.Length, Strings.DoNotDeclareFunctionInNestedBlocks);
                }

                body = new CodeBlock(new[] { body }); // для того, чтобы не дублировать код по декларации функции,
                // она оборачивается в блок, который сделает самовыпил на втором этапе, но перед этим корректно объявит функцию.
            }

            CodeNode elseBody = null;

            var pos = i;

            while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }

            if (i < state.Code.Length && !combinedBody && state.Code[i] == ';')
            {
                do
                {
                    i++;
                }while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]));
            }

            if (Parser.Validate(state.Code, "else", ref i))
            {
                while (Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }

                elseBody = Parser.Parse(state, ref i, 0);
                if (elseBody is FunctionDefinition)
                {
                    if (state.message != null)
                    {
                        state.message(MessageLevel.CriticalWarning, elseBody.Position, elseBody.Length, Strings.DoNotDeclareFunctionInNestedBlocks);
                    }

                    elseBody = new CodeBlock(new[] { elseBody }); // для того, чтобы не дублировать код по декларации функции,
                    // она оборачивается в блок, который сделает самовыпил на втором этапе, но перед этим корректно объявит функцию.
                }
            }
            else
            {
                i = pos;
            }

            pos   = index;
            index = i;
            return(new IfElse()
            {
                then = body,
                condition = condition,
                @else = elseBody,
                Position = pos,
                Length = index - pos
            });
        }
Example #4
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }

            if (!Parser.Validate(state.Code, "do", ref i) || !Parser.IsIdentifierTerminator(state.Code[i]))
            {
                return(null);
            }

            int labelsCount = state.LabelsCount;

            state.LabelsCount = 0;
            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            state.AllowBreak.Push(true);
            state.AllowContinue.Push(true);
            int ccs  = state.ContiniesCount;
            int cbs  = state.BreaksCount;
            var body = Parser.Parse(state, ref i, 0);

            if (body is FunctionDefinition)
            {
                if (state.Strict)
                {
                    ExceptionHelper.Throw((new SyntaxError("In strict mode code, functions can only be declared at top level or immediately within another function.")));
                }
                state.Message?.Invoke(MessageLevel.CriticalWarning, body.Position, body.Length, "Do not declare function in nested blocks.");
                body = new CodeBlock(new[] { body }); // для того, чтобы не дублировать код по декларации функции,
                // она оборачивается в блок, который сделает самовыпил на втором этапе, но перед этим корректно объявит функцию.
            }
            state.AllowBreak.Pop();
            state.AllowContinue.Pop();
            if (!(body is CodeBlock) && state.Code[i] == ';')
            {
                i++;
            }
            while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (i >= state.Code.Length)
            {
                ExceptionHelper.Throw(new SyntaxError("Unexpected end of source."));
            }
            if (!Parser.Validate(state.Code, "while", ref i))
            {
                ExceptionHelper.Throw((new SyntaxError("Expected \"while\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
            }
            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (state.Code[i] != '(')
            {
                ExceptionHelper.Throw((new SyntaxError("Expected \"(\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
            }
            do
            {
                i++;
            }while (Tools.IsWhiteSpace(state.Code[i]));
            var condition = Parser.Parse(state, ref i, CodeFragmentType.Expression);

            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (state.Code[i] != ')')
            {
                ExceptionHelper.Throw((new SyntaxError("Expected \")\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
            }
            i++;
            var pos = index;

            index = i;
            return(new DoWhile
            {
                allowRemove = ccs == state.ContiniesCount && cbs == state.BreaksCount,
                body = body,
                condition = condition,
                labels = state.Labels.GetRange(state.Labels.Count - labelsCount, labelsCount).ToArray(),
                Position = pos,
                Length = index - pos
            });
        }
Example #5
0
        private void Callback(object obj)
        {
            ParseInfo info = (ParseInfo)obj;

            Parse(info.Obj, info.ResultHandler, info.Operation);
        }
 public static bool EventPlayerDefaultCall(IIndexReferencer referencer, IExpression parent, ParseInfo parseInfo)
 => referencer.VariableType == VariableType.Player && (parent == null && (parent.ReturningScope() != null && parent.ReturningScope() != parseInfo.TranslateInfo.PlayerVariableScope));
Example #7
0
        public void Parse(IModel model, InputCharInfo inputChar, System.Action callback)
        {
            var text = model.Content;

            try
            {
                var parseInfo = new ParseInfo();
                parseInfo.Content = text;
                parseInfo.Index   = 0;
                parseInfo.Type    = model.ParseType;
                var    parseInfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(parseInfo);
                string json           = null;


                if (!ConnectProxy.Instance().Send(parseInfo_json))
                {
                    model.SetParsed(false);
                    return;
                }
                json = ConnectProxy.Instance().Read();


                if (json == null)
                {
                    model.SetParsed(false);
                    return;
                }
                IParseModule module = null;
                try
                {
                    if (model.ParseType == CodeHelper.Core.Parser.ParseType.XmlModel)
                    {
                        module = JsonConvert.DeserializeObject <XmModelDB>(json);
                        //XmModelDB.Current.InputChar = inputChar;
                    }
                    else if (model.ParseType == CodeHelper.Core.Parser.ParseType.DataModel)
                    {
                        module = JsonConvert.DeserializeObject <DmModelDB>(json);
                        //DmModelDB.Current.InputChar = inputChar;
                    }
                    else if (model.ParseType == Core.Parser.ParseType.DataView)
                    {
                        module = JsonConvert.DeserializeObject <DataViewDB>(json);
                        //DataViewDB.Current.InputChar = inputChar;
                    }
                    else if (model.ParseType == Core.Parser.ParseType.ViewModel)
                    {
                        module = JsonConvert.DeserializeObject <ViewModelDB>(json);
                        ViewModelDB.Current           = module as ViewModelDB;
                        ViewModelDB.Current.InputChar = inputChar;
                    }
                    else if (model.ParseType == Core.Parser.ParseType.WorkFlow)
                    {
                        var program = JsonConvert.DeserializeObject <Program>(json);
                        module = new WorkflowDB();
                        ((WorkflowDB)module).Program = program;
                        WorkflowDB.Current           = module as WorkflowDB;
                        WorkflowDB.Current.InputChar = inputChar;
                        module.Name = System.IO.Path.GetFileNameWithoutExtension(model.File);
                    }
                }
                catch (Exception e)
                {
                    this.Errors.Add(new Core.Error.ParseErrorInfo()
                    {
                        FileId    = model.FileId,
                        File      = model.File,
                        ErrorType = Core.Error.ErrorType.Error,
                        Message   = "模块解析错误: " + e.Message
                    });
                }
                if (module == null)
                {
                    model.SetParsed(false);

                    return;
                }

                module.File   = model.File;
                module.FileId = model.FileId;

                module.Initialize();

                module.Wise();

                module.FileId = model.FileId;

                model.SetParsed(true);

                module.Errors.ForEach(x => { x.File = model.File; x.FileId = model.FileId; });

                if (module.Errors != null)
                {
                    module.Errors.ForEach(x => Errors.Add(x));
                }
            }
            catch (Exception e)
            {
                this.Errors.Add(new Core.Error.ParseErrorInfo()
                {
                    FileId    = model.FileId,
                    File      = model.File,
                    ErrorType = Core.Error.ErrorType.Error,
                    Message   = "模块解析错误: " + e.Message
                });
                Console.Out.WriteLine(e.StackTrace);
            }
            finally
            {
                if (callback != null)
                {
                    callback();
                }
            }
        }
Example #8
0
        public static QNode[] Parse(string text, int index = 0, int state = 0)
        {
            var stack = new Stack<ParseInfo>();
              var info = new ParseInfo();

              Action PopWhileSingle = () =>
              {
            for (; stack.Count > 0 && info.isSingle == true; )
            {
              var parent = stack.Pop();
              parent.PushChild(info);
              info = parent;
            }
              };
              var lexemBuilder = new System.Text.StringBuilder();
              for (; ; )
              {
            char ch = index < text.Length ? text[index] : (char)0;
            var isEnd = index >= text.Length;
            if (state == 0)
            {
              if (index >= text.Length)
              {
            PopWhileSingle();
            if (stack.Count > 0)
              throw new Exception($"Не хватает закрывающихся скобок - '{stack.Count}' шт.");

            return info.allElements;
              }
              else if (char.IsWhiteSpace(ch))
              {
            index++;
            continue;
              }
              else if (ch == Quote)
              {
            state = 2;
            lexemBuilder = new System.Text.StringBuilder();
            index++;
            continue;
              }
              else if (ch == DoubleQuote)
              {
            state = 3;
            lexemBuilder = new System.Text.StringBuilder();
            index++;
            continue;
              }
              else if (char.IsLetter(ch) || char.IsDigit(ch) || ch == '-' || ch == '_')
              {
            state = 1;
            lexemBuilder = new System.Text.StringBuilder();
            lexemBuilder.Append(ch);
            index++;
            continue;
              }
              else if (ch == ':' && (index + 1) < text.Length && text[index + 1] == ':')
              {
            state = 1;
            lexemBuilder = new System.Text.StringBuilder();
            lexemBuilder.Append(text.Substring(index, 2));
            index += 2;
              }
              else if (ch == ':')
              {
            stack.Push(info);
            info = new ParseInfo { isSingle = true };
            index++;
            continue;
              }
              else if (ch == '{' || ch == '(')
              {
            stack.Push(info);
            info = new ParseInfo();
            index++;
            continue;
              }
              else if (ch == '}' || ch == ')')
              {
            PopWhileSingle();
            var parentInfo = stack.Pop();
            parentInfo.PushChild(info);
            info = parentInfo;
            index++;
            continue;
              }
              else if (ch == ',' || ch == ';')
              {
            PopWhileSingle();
            info.PushCurrent(null);
            index++;
            continue;
              }
              else if (ch == '/' && (index + 1) < text.Length && text[index + 1] == '/')
              {
            state = 4;
            lexemBuilder = new System.Text.StringBuilder();
            index += 2;
            continue;
              }
              else
              {
            throw new Exception(string.Format("invalid char in index:{0}", index));
            //index++;
            //continue;
              }
            }
            else if (state == 1)
            {
              if (char.IsLetter(ch) || char.IsDigit(ch) || ch == '-' || ch == '_')
              {
            lexemBuilder.Append(ch);
            index++;
            continue;
              }
              else
              {
            var q = new QNode(lexemBuilder.ToString());
            info.PushCurrent(q);
            state = 0;
            continue;
              }
            }
            else if (state == 2 || state == 3)
            {
              var quote = state == 2 ? Quote : DoubleQuote;
              if (isEnd)
            throw new Exception(string.Format("не законченная строка '{0}'", lexemBuilder));
              else if (ch == quote)
              {
            if ((index + 1) < text.Length && text[index + 1] == quote)
            {
              lexemBuilder.Append(quote);
              index += 2;
              continue;
            }
            else
            {
              var q = new QNode(lexemBuilder.ToString());
              info.PushCurrent(q);
              state = 0;
              index++;
              continue;
            }
              }
              else
              {
            lexemBuilder.Append(ch);
            index++;
            continue;
              }
            }
            else if (state == 4)
            {
              if (ch == '\r' || ch == '\n')
              {
            //var q = new QElement(lexemBuilder.ToString());
            //info.PushCurrent(q);
            state = 0;
            index++;
            continue;
              }
              else
              {
            lexemBuilder.Append(ch);
            index++;
            continue;
              }
            }

              }
        }
Example #9
0
            void Parse(IModel model, int charIndex, System.Action callback)
            {
                var text = model.Content;

                ThreadPool.QueueUserWorkItem(o =>
                {
                    try
                    {
                        var parseInfo      = new ParseInfo();
                        parseInfo.Content  = text;
                        parseInfo.Index    = charIndex;
                        parseInfo.Type     = model.ParseType;
                        var parseInfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(parseInfo);
                        string json        = null;

                        lock (this.syncObj)
                        {
                            if (!ConnectProxy.Instance().Send(parseInfo_json))
                            {
                                model.SetParsed(false);
                                return;
                            }
                            json = ConnectProxy.Instance().Read();
                        }

                        if (json == null)
                        {
                            model.SetParsed(false);
                            return;
                        }
                        IParseModule module = null;
                        try
                        {
                            if (model.ParseType == CodeHelper.Core.Parser.ParseType.XmlModel)
                            {
                                module = JsonConvert.DeserializeObject <XmModelDB>(json);
                            }
                            else if (model.ParseType == CodeHelper.Core.Parser.ParseType.DataModel)
                            {
                                var program = JsonConvert.DeserializeObject <DbProgram>(json);
                                module      = new DmModelDB();
                                ((DmModelDB)module).Program = program;
                                module.Name = System.IO.Path.GetFileNameWithoutExtension(model.File);
                            }
                            else if (model.ParseType == Core.Parser.ParseType.DataView)
                            {
                                module = JsonConvert.DeserializeObject <DataViewDB>(json);
                            }
                            else if (model.ParseType == Core.Parser.ParseType.ViewModel)
                            {
                                module = JsonConvert.DeserializeObject <ViewModelDB>(json);
                                ViewModelDB.Current = module as ViewModelDB;
                            }
                            else if (model.ParseType == Core.Parser.ParseType.WorkFlow)
                            {
                                var program = JsonConvert.DeserializeObject <Program>(json);
                                module      = new WorkflowDB();
                                ((WorkflowDB)module).Program = program;
                                WorkflowDB.Current           = module as WorkflowDB;
                                module.Name = System.IO.Path.GetFileNameWithoutExtension(model.File);
                            }
                        }
                        catch (Exception e)
                        {
                            this.AddError(new Core.Error.ParseErrorInfo()
                            {
                                FileId    = model.FileId,
                                File      = model.File,
                                ErrorType = Core.Error.ErrorType.Error,
                                Message   = "模块解析错误: " + e.Message
                            });
                        }
                        if (module == null)
                        {
                            //this.IsWiseCompleted = true;
                            model.SetParsed(false);
                            OnRemoveModule(model.FileId);
                            return;
                        }

                        module.Initialize();

                        module.FileId = model.FileId;

                        model.SetParsed(true);

                        module.Errors.ForEach(x => { x.File = model.File; x.FileId = model.FileId; });

                        //OnUpdateModule(model.FileId, module);

                        this.waitingWiseModules.Add(module);

                        if (module.Errors != null)
                        {
                            module.Errors.ForEach(x => AddError(x));
                        }
                    }
                    catch (Exception e)
                    {
                        this.AddError(new Core.Error.ParseErrorInfo()
                        {
                            FileId    = model.FileId,
                            File      = model.File,
                            ErrorType = Core.Error.ErrorType.Error,
                            Message   = "模块解析错误: " + e.Message
                        });
                        Console.Out.WriteLine(e.StackTrace);
                    }
                    finally
                    {
                        if (callback != null)
                        {
                            callback();
                        }

                        this.waitingParseModels.Take();

                        if (this.waitingParseModels.Count == 0)
                        {
                            parseEvent.Set();
                        }
                        else
                        {
                        }
                    }
                });
            }
Example #10
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int  position = index;
            bool sroot    = position == 0 && state.AllowDirectives;

            if (!sroot)
            {
                if (state.Code[position] != '{')
                {
                    throw new ArgumentException("code (" + position + ")");
                }
                position++;
            }

            Tools.SkipSpaces(state.Code, ref position);

            var body = new List <CodeNode>();

#if DEBUG
            HashSet <string> directives = null;
#endif

            var oldFunctionScopeLevel = state.FunctionScopeLevel;
            state.LexicalScopeLevel++;
            if (state.AllowDirectives)
            {
                state.FunctionScopeLevel = state.LexicalScopeLevel;
            }

            var oldVariablesCount          = state.Variables.Count;
            VariableDescriptor[] variables = null;
            state.LabelsCount = 0;

            var allowDirectives = state.AllowDirectives;
            using (state.WithCodeContext())
            {
                state.CodeContext &= ~CodeContext.AllowDirectives;

                try
                {
                    if (allowDirectives)
                    {
                        int start         = position;
                        var hasDirectives = false;
                        do
                        {
                            var s = position;
                            if (position >= state.Code.Length)
                            {
                                break;
                            }

                            if (Parser.ValidateValue(state.Code, ref position))
                            {
                                while (position < state.Code.Length && Tools.IsWhiteSpace(state.Code[position]))
                                {
                                    position++;
                                }
                                if (position < state.Code.Length && (Parser.IsOperator(state.Code[position]) ||
                                                                     Parser.Validate(state.Code, "instanceof", position) ||
                                                                     Parser.Validate(state.Code, "in", position)))
                                {
                                    position = s;
                                    break;
                                }

                                var t = s;
                                if (Parser.ValidateString(state.Code, ref t, true))
                                {
                                    var str = state.Code.Substring(s + 1, t - s - 2);
                                    if (str == "use strict")
                                    {
                                        state.CodeContext |= CodeContext.Strict;
                                    }

                                    hasDirectives = true;
#if DEBUG
                                    if (directives == null)
                                    {
                                        directives = new HashSet <string>();
                                    }

                                    directives.Add(str);
#endif
                                }
                                else
                                {
                                    position = s;
                                    break;
                                }
                            }
                            else if (state.Code[position] == ';')
                            {
                                if (!hasDirectives)
                                {
                                    break;
                                }

                                do
                                {
                                    position++;
                                } while (position < state.Code.Length && Tools.IsWhiteSpace(state.Code[position]));
                            }
                            else
                            {
                                break;
                            }
                        }while (true);
                        position = start;
                    }

                    for (var j = body.Count; j-- > 0;)
                    {
                        (body[j] as Constant).value._oValue = Tools.Unescape((body[j] as Constant).value._oValue.ToString(), state.Strict);
                    }

                    bool expectSemicolon = false;
                    while ((sroot && position < state.Code.Length) || (!sroot && state.Code[position] != '}'))
                    {
                        var t = Parser.Parse(state, ref position, 0);
                        if (t == null)
                        {
                            if (position < state.Code.Length)
                            {
                                if (sroot && state.Code[position] == '}')
                                {
                                    ExceptionHelper.Throw(new SyntaxError("Unexpected symbol \"}\" at " + CodeCoordinates.FromTextPosition(state.Code, position, 0)));
                                }

                                if ((state.Code[position] == ';' || state.Code[position] == ','))
                                {
                                    if (state.Message != null && !expectSemicolon)
                                    {
                                        state.Message(MessageLevel.Warning, position, 1, "Unnecessary semicolon.");
                                    }

                                    position++;
                                }

                                expectSemicolon = false;
                            }

                            continue;
                        }

                        expectSemicolon = !(t is EntityDefinition);

                        body.Add(t);
                    }
                }
                finally
                {
                    if (oldVariablesCount != state.Variables.Count)
                    {
                        variables = extractVariables(state, oldVariablesCount);
                    }

                    state.FunctionScopeLevel = oldFunctionScopeLevel;
                    state.LexicalScopeLevel--;
                }

                if (!sroot)
                {
                    position++;
                }

                int startPos = index;
                index = position;
                return(new CodeBlock(body.ToArray())
                {
                    _strict = state.Strict,
                    _variables = variables ?? emptyVariables,
                    Position = startPos,
                    code = state.SourceCode,
                    Length = position - startPos,
#if DEBUG
                    directives = directives
#endif
                });
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public static Transaction Parse(ParseInfo info, params String[] data)
        {
            var splitted = info.HasFlag(ParseInfo.CVS) ? data[0].Split(',') : data;
            switch (info & ~ParseInfo.CVS)
            {
                case ParseInfo.ING:

                    DateTime ingDate = DateTime.Now;
                        if (!DateTime.TryParse(splitted[0], out ingDate))
                            ingDate = DateTime.ParseExact(splitted[0], "yyyyMMdd", CultureInfo.CurrentCulture);

                    var ingTime = DateTime.Now;
                    var ingTimestamp = splitted[1].Contains(' ') ? splitted[1].Split(' ') : null;

                    var ingDesc = TryExtractingDateAndTime(ingTimestamp, ref ingDate, ref ingTime);
                    splitted[1] = ingDesc ?? splitted[1];

                    if (ingDesc == null)
                        if (!DateTime.TryParse(splitted[0], out ingDate))
                            ingDate = DateTime.ParseExact(splitted[0], "yyyyMMdd", CultureInfo.CurrentCulture);

                    return Transaction.Generate(ingDate, splitted[1].Trim(), splitted[2], splitted[3],
                        (Code)Enum.Parse(typeof(Code), splitted[4]), (splitted[5].Contains("Af") ? -1 : 1) * Decimal.Parse(splitted[6], NumberStyles.Currency), splitted[7]);

                case ParseInfo.Rabobank:

                    DateTime raboDate = DateTime.Now;
                        if (!DateTime.TryParse(splitted[2], out raboDate))
                            raboDate = DateTime.ParseExact(splitted[2], "yyyyMMdd", CultureInfo.CurrentCulture);

                    var raboTime = DateTime.Now;
                    var raboTimestamp = splitted[10].Contains(' ') ? splitted[10].Split(' ') : null;

                    var raboDesc = TryExtractingDateAndTime(raboTimestamp, ref raboDate, ref raboTime);
                    splitted[10] = raboDesc ?? splitted[10];

                    if (raboDesc == null)
                        if (!DateTime.TryParse(splitted[2], out raboDate))
                            raboDate = DateTime.ParseExact(splitted[2], "yyyyMMdd", CultureInfo.CurrentCulture);

                    var numberFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
                    numberFormat.CurrencyDecimalSeparator = ".";

                    return Transaction.Generate(raboDate, splitted[6].Trim(), splitted[0], splitted[5],
                        (Code)Enum.Parse(typeof(Code), splitted[8].ToUpper()), (splitted[3].Contains("D") ? 1 : 1) * Decimal.Parse(splitted[4], NumberStyles.Currency, numberFormat),
                        splitted[10], splitted[1]);

                case ParseInfo.PayPal:
                    return Transaction.Generate(new Date(DateTime.Parse(splitted[0])), new Time(DateTime.Parse(splitted[1])), null, //TimeZoneInfo.FindSystemTimeZoneById("2")
                        splitted[3], Code.Paypal, splitted[5], Decimal.Parse(splitted[6]), splitted[7], splitted[8], splitted[9]); //(Code)Enum.Parse(typeof(Code), splitted[4])
            }

            throw new NotSupportedException("No parsing available for " + info.ToString());
        }
        internal static CodeNode Parse(ParseInfo state, ref int index, bool forForLoop)
        {
            int position = index;

            Tools.SkipSpaces(state.Code, ref position);

            var mode = VariableKind.FunctionScope;

            if (Parser.Validate(state.Code, "var ", ref position))
            {
                mode = VariableKind.FunctionScope;
            }
            else if (Parser.Validate(state.Code, "let ", ref position))
            {
                mode = VariableKind.LexicalScope;
            }
            else if (Parser.Validate(state.Code, "const ", ref position))
            {
                mode = VariableKind.ConstantInLexicalScope;
            }
            else
            {
                return(null);
            }

            var level        = mode <= VariableKind.FunctionScope ? state.functionScopeLevel : state.lexicalScopeLevel;
            var initializers = new List <Expression>();
            var names        = new List <string>();
            int s            = position;

            while ((state.Code[position] != ';') && (state.Code[position] != '}') && !Tools.IsLineTerminator(state.Code[position]))
            {
                Tools.SkipSpaces(state.Code, ref position);

                if (state.Code[position] != '[' && state.Code[position] != '{' && !Parser.ValidateName(state.Code, position, state.strict))
                {
                    if (Parser.ValidateName(state.Code, ref position, false, true, state.strict))
                    {
                        ExceptionHelper.ThrowSyntaxError('\"' + Tools.Unescape(state.Code.Substring(s, position - s), state.strict) + "\" is a reserved word, but used as a variable. " + CodeCoordinates.FromTextPosition(state.Code, s, position - s));
                    }
                    ExceptionHelper.ThrowSyntaxError("Invalid variable definition at " + CodeCoordinates.FromTextPosition(state.Code, s, position - s));
                }

                var expression = ExpressionTree.Parse(state, ref position, processComma: false, forForLoop: forForLoop);
                if (expression is VariableReference)
                {
                    var name = expression.ToString();
                    if (state.strict)
                    {
                        if (name == "arguments" || name == "eval")
                        {
                            ExceptionHelper.ThrowSyntaxError("Varible name cannot be \"arguments\" or \"eval\" in strict mode", state.Code, s, position - s);
                        }
                    }

                    names.Add(name);
                    initializers.Add(expression);
                }
                else
                {
                    bool valid = false;
                    var  expr  = expression as ExpressionTree;
                    if (expr != null)
                    {
                        if (expr.Type == OperationType.None && expr._right == null)
                        {
                            expr = expr._left as ExpressionTree;
                        }
                        valid |= expr != null && expr.Type == OperationType.Assignment;

                        if (valid)
                        {
                            if (expr._left is ObjectDesctructor)
                            {
                                var expressions = (expr._left as ObjectDesctructor).GetTargetVariables();
                                for (var i = 0; i < expressions.Count; i++)
                                {
                                    names.Add(expressions[i].ToString());
                                    initializers.Add(expressions[i]);
                                }

                                initializers.Add(expr);
                            }
                            else
                            {
                                names.Add(expr._left.ToString());
                                initializers.Add(expression);
                            }
                        }
                    }
                    else
                    {
                        var cnst = expression as Constant;
                        valid = cnst != null && cnst.value == JSValue.undefined;
                        if (valid)
                        {
                            initializers.Add(expression);
                            names.Add(cnst.value.ToString());
                        }
                    }

                    if (!valid)
                    {
                        ExceptionHelper.ThrowSyntaxError("Invalid variable initializer", state.Code, position);
                    }
                }

                s = position;

                if (position >= state.Code.Length)
                {
                    break;
                }

                Tools.SkipSpaces(state.Code, ref s);
                if (s >= state.Code.Length)
                {
                    break;
                }
                if (state.Code[s] == ',')
                {
                    position = s + 1;
                    Tools.SkipSpaces(state.Code, ref position);
                }
                else
                {
                    break;
                }
            }

            if (names.Count == 0)
            {
                throw new InvalidOperationException("code (" + position + ")");
            }

            if (!forForLoop && position < state.Code.Length && state.Code[position] == ';')
            {
                position++;
            }
            else
            {
                position = s;
            }

            var variables = new VariableDescriptor[names.Count];

            for (int i = 0, skiped = 0; i < names.Count; i++)
            {
                bool skip = false;
                for (var j = 0; j < state.Variables.Count - i + skiped; j++)
                {
                    if (state.Variables[j].name == names[i] && state.Variables[j].definitionScopeLevel >= level)
                    {
                        if (state.Variables[j].lexicalScope && mode > VariableKind.FunctionScope)
                        {
                            ExceptionHelper.ThrowSyntaxError(string.Format(Strings.IdentifierAlreadyDeclared, names[i]), state.Code, index);
                        }

                        skip         = true;
                        variables[i] = state.Variables[j];
                        skiped++;
                        break;
                    }
                }

                if (skip)
                {
                    continue;
                }

                variables[i] = new VariableDescriptor(names[i], level)
                {
                    lexicalScope = mode > VariableKind.FunctionScope,
                    isReadOnly   = mode == VariableKind.ConstantInLexicalScope
                };

                state.Variables.Add(variables[i]);
            }

            var pos = index;

            index = position;
            return(new VariableDefinition(variables, initializers.ToArray(), mode)
            {
                Position = pos,
                Length = index - pos
            });
        }
 internal static CodeNode Parse(ParseInfo state, ref int index)
 {
     return(Parse(state, ref index, false));
 }
Example #14
0
 public void SetCmdInfo(ParseInfo info)
 {
     ParameterVersions = info.ParameterVersions;
 }
Example #15
0
 private HttpResponseDatagram(byte[] buffer, int offset, ParseInfo parseInfo)
     : base(buffer, offset, parseInfo.Length, parseInfo.Version, parseInfo.Header, parseInfo.Body)
 {
     StatusCode   = parseInfo.StatusCode;
     ReasonPhrase = parseInfo.ReasonPhrase;
 }
Example #16
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            //string code = state.Code;
            int i = index;

            if (!Parser.Validate(state.Code, "while (", ref i) && !Parser.Validate(state.Code, "while(", ref i))
            {
                return(null);
            }
            int labelsCount = state.LabelsCount;

            state.LabelsCount = 0;
            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            var condition = Parser.Parse(state, ref i, CodeFragmentType.Expression);

            while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (i >= state.Code.Length)
            {
                ExceptionHelper.Throw(new SyntaxError(Strings.UnexpectedEndOfSource));
            }
            if (state.Code[i] != ')')
            {
                throw new ArgumentException("code (" + i + ")");
            }
            do
            {
                i++;
            }while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]));
            if (i >= state.Code.Length)
            {
                ExceptionHelper.ThrowSyntaxError(Strings.UnexpectedEndOfSource);
            }
            state.AllowBreak.Push(true);
            state.AllowContinue.Push(true);
            int ccs  = state.continiesCount;
            int cbs  = state.breaksCount;
            var body = Parser.Parse(state, ref i, 0);

            if (body is FunctionDefinition)
            {
                if (state.message != null)
                {
                    state.message(MessageLevel.CriticalWarning, body.Position, body.Length, Strings.DoNotDeclareFunctionInNestedBlocks);
                }
                body = new CodeBlock(new[] { body }); // для того, чтобы не дублировать код по декларации функции,
                // она оборачивается в блок, который сделает самовыпил на втором этапе, но перед этим корректно объявит функцию.
            }
            state.AllowBreak.Pop();
            state.AllowContinue.Pop();
            var pos = index;

            index = i;
            return(new While()
            {
                allowRemove = ccs == state.continiesCount && cbs == state.breaksCount,
                body = body,
                condition = condition,
                labels = state.Labels.GetRange(state.Labels.Count - labelsCount, labelsCount).ToArray(),
                Position = pos,
                Length = index - pos
            });
        }
Example #17
0
 public static CodeNode Parse(ParseInfo state, ref int index)
 {
     return(Parse(state, ref index, TemplateStringMode.Regular));
 }
Example #18
0
        private void Setup(MethodInfo method)
        {
            var parseMethodName = "Parse" + method.Name;
            var parseMethod = typeof(ConditionFacade).GetMethod(parseMethodName, BindingFlags.NonPublic | BindingFlags.Static);

            if (parseMethod == null)
                throw new MissingMethodException(typeof(ConditionFacade).Name + "." + parseMethodName);

            var parseDelegate = (ParseDelegate)ParseDelegate.CreateDelegate(typeof(ParseDelegate), parseMethod);

            var info = new ParseInfo()
            {
                Method = method,
                Negatable = IsNegatable(method),
                Parse = parseDelegate
            };

            _parseInfoLookUp[method.Name] = info;
        }
Example #19
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            if (!Parser.Validate(state.Code, "class", ref i))
            {
                return(null);
            }

            Tools.SkipSpaces(state.Code, ref i);

            string     name     = null;
            Expression baseType = null;

            if (!Parser.Validate(state.Code, "extends ", i))
            {
                var n = i;
                if (Parser.ValidateName(state.Code, ref i, true))
                {
                    name = state.Code.Substring(n, i - n);
                }

                while (Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }
            }
            if (Parser.Validate(state.Code, "extends ", ref i))
            {
                var n = i;
                if (!Parser.ValidateName(state.Code, ref i, true) && !Parser.Validate(state.Code, "null", ref i))
                {
                    ExceptionHelper.ThrowSyntaxError("Invalid base class name", state.Code, i);
                }

                var baseClassName = state.Code.Substring(n, i - n);
                if (baseClassName == "null")
                {
                    baseType = new Constant(JSValue.@null);
                }
                else
                {
                    baseType = new Variable(baseClassName, 1);
                }

                baseType.Position = n;
                baseType.Length   = i - n;

                while (Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }
            }

            if (state.Code[i] != '{')
            {
                ExceptionHelper.ThrowSyntaxError(Strings.UnexpectedToken, state.Code, i);
            }

            FunctionDefinition ctor   = null;
            ClassDefinition    result = null;

            var flds = new Dictionary <string, MemberDescriptor>();
            var computedProperties = new List <MemberDescriptor>();

            while (state.Code[i] != '}')
            {
                using (state.WithCodeContext(CodeContext.Strict | CodeContext.InExpression))
                {
                    do
                    {
                        i++;
                    } while (Tools.IsWhiteSpace(state.Code[i]) || state.Code[i] == ';');

                    int s = i;
                    if (state.Code[i] == '}')
                    {
                        break;
                    }

                    bool @static = Parser.Validate(state.Code, "static", ref i);
                    if (@static)
                    {
                        Tools.SkipSpaces(state.Code, ref i);
                        s = i;
                    }

                    bool @async = Parser.Validate(state.Code, "async", ref i);
                    if (@async)
                    {
                        Tools.SkipSpaces(state.Code, ref i);
                        s = i;
                    }

                    bool getOrSet = Parser.Validate(state.Code, "get", ref i) || Parser.Validate(state.Code, "set", ref i);
                    if (getOrSet)
                    {
                        Tools.SkipSpaces(state.Code, ref i);
                    }

                    var asterisk = state.Code[i] == '*';
                    if (asterisk)
                    {
                        do
                        {
                            i++;
                        }while (Tools.IsWhiteSpace(state.Code[i]));
                    }

                    if (Parser.Validate(state.Code, "[", ref i))
                    {
                        var propertyName = ExpressionTree.Parse(state, ref i, false, false, false, true, false);
                        while (Tools.IsWhiteSpace(state.Code[i]))
                        {
                            i++;
                        }
                        if (state.Code[i] != ']')
                        {
                            ExceptionHelper.ThrowSyntaxError("Expected ']'", state.Code, i);
                        }
                        do
                        {
                            i++;
                        }while (Tools.IsWhiteSpace(state.Code[i]));

                        CodeNode initializer;
                        if (state.Code[i] == '(')
                        {
                            initializer = FunctionDefinition.Parse(state, ref i, asterisk ? FunctionKind.AnonymousGenerator : FunctionKind.AnonymousFunction);
                        }
                        else
                        {
                            initializer = ExpressionTree.Parse(state, ref i);
                        }

                        switch (state.Code[s])
                        {
                        case 'g':
                        {
                            computedProperties.Add(new MemberDescriptor((Expression)propertyName, new PropertyPair((Expression)initializer, null), @static));
                            break;
                        }

                        case 's':
                        {
                            computedProperties.Add(new MemberDescriptor((Expression)propertyName, new PropertyPair(null, (Expression)initializer), @static));
                            break;
                        }

                        default:
                        {
                            computedProperties.Add(new MemberDescriptor((Expression)propertyName, (Expression)initializer, @static));
                            break;
                        }
                        }
                    }
                    else if (getOrSet)
                    {
                        i = s;
                        var mode             = state.Code[i] == 's' ? FunctionKind.Setter : FunctionKind.Getter;
                        var propertyAccessor = FunctionDefinition.Parse(state, ref i, mode) as FunctionDefinition;
                        var accessorName     = (@static ? "static " : "") + propertyAccessor._name;
                        if (!flds.ContainsKey(accessorName))
                        {
                            var propertyPair = new PropertyPair
                                               (
                                mode == FunctionKind.Getter ? propertyAccessor : null,
                                mode == FunctionKind.Setter ? propertyAccessor : null
                                               );
                            flds.Add(accessorName, new MemberDescriptor(new Constant(propertyAccessor._name), propertyPair, @static));
                        }
                        else
                        {
                            var vle = flds[accessorName].Value as PropertyPair;

                            if (vle == null)
                            {
                                ExceptionHelper.Throw((new SyntaxError("Try to define " + mode.ToString().ToLowerInvariant() + " for defined field at " + CodeCoordinates.FromTextPosition(state.Code, s, 0))));
                            }

                            do
                            {
                                if (mode == FunctionKind.Getter)
                                {
                                    if (vle.Getter == null)
                                    {
                                        vle.Getter = propertyAccessor;
                                        break;
                                    }
                                }
                                else
                                {
                                    if (vle.Setter == null)
                                    {
                                        vle.Setter = propertyAccessor;
                                        break;
                                    }
                                }

                                ExceptionHelper.ThrowSyntaxError("Try to redefine " + mode.ToString().ToLowerInvariant() + " of " + propertyAccessor.Name, state.Code, s);
                            }while (false);
                        }
                    }
                    else
                    {
                        i = s;
                        string fieldName = null;
                        if (state.Code[i] == '*')
                        {
                            do
                            {
                                i++;
                            }while (Tools.IsWhiteSpace(state.Code[i]));
                        }

                        if (Parser.ValidateName(state.Code, ref i, false, true, state.Strict))
                        {
                            fieldName = Tools.Unescape(state.Code.Substring(s, i - s), state.Strict);
                        }
                        else if (Parser.ValidateValue(state.Code, ref i))
                        {
                            double d = 0.0;
                            int    n = s;
                            if (Tools.ParseNumber(state.Code, ref n, out d))
                            {
                                fieldName = Tools.DoubleToString(d);
                            }
                            else if (state.Code[s] == '\'' || state.Code[s] == '"')
                            {
                                fieldName = Tools.Unescape(state.Code.Substring(s + 1, i - s - 2), state.Strict);
                            }
                        }

                        if (fieldName == null)
                        {
                            ExceptionHelper.Throw((new SyntaxError("Invalid member name at " + CodeCoordinates.FromTextPosition(state.Code, s, i - s))));
                        }

                        if (fieldName == "constructor")
                        {
                            if (@static)
                            {
                                ExceptionHelper.ThrowSyntaxError(Strings.ConstructorCannotBeStatic, state.Code, s);
                            }
                            if (ctor != null)
                            {
                                ExceptionHelper.ThrowSyntaxError("Trying to redefinition constructor", state.Code, s);
                            }

                            state.CodeContext |= CodeContext.InClassConstructor;
                        }
                        else if (@static)
                        {
                            fieldName          = "static " + fieldName;
                            state.CodeContext |= CodeContext.InStaticMember;
                        }
                        if (flds.ContainsKey(fieldName))
                        {
                            ExceptionHelper.Throw(new SyntaxError("Trying to redefinition member \"" + fieldName + "\" at " + CodeCoordinates.FromTextPosition(state.Code, s, i - s)));
                        }

                        state.CodeContext |= CodeContext.InClassDefinition;
                        state.CodeContext &= ~CodeContext.InGenerator;

                        if (async)
                        {
                            state.CodeContext |= CodeContext.InAsync;
                        }

                        i = s;
                        var method = FunctionDefinition.Parse(state, ref i, async ? FunctionKind.AsyncMethod : FunctionKind.Method) as FunctionDefinition;
                        if (method == null)
                        {
                            ExceptionHelper.ThrowSyntaxError("Unable to parse method", state.Code, i);
                        }

                        if (fieldName == "constructor")
                        {
                            ctor = method;
                        }
                        else
                        {
                            flds[fieldName] = new MemberDescriptor(new Constant(method._name), method, @static);
                        }
                    }
                }
            }

            if (ctor == null)
            {
                string ctorCode;
                int    ctorIndex = 0;
                if (baseType != null && !(baseType is Constant))
                {
                    ctorCode = "constructor(...args) { super(...args); }";
                }
                else
                {
                    ctorCode = "constructor(...args) { }";
                }

                var nestedParseInfo = state.AlternateCode(ctorCode);
                using (nestedParseInfo.WithCodeContext(CodeContext.InClassConstructor | CodeContext.InClassDefinition))
                    ctor = (FunctionDefinition)FunctionDefinition.Parse(nestedParseInfo, ref ctorIndex, FunctionKind.Method);
            }

            result = new ClassDefinition(name, baseType, new List <MemberDescriptor>(flds.Values).ToArray(), ctor as FunctionDefinition, computedProperties.ToArray());

            if ((state.CodeContext & CodeContext.InExpression) == 0)
            {
                if (string.IsNullOrEmpty(name))
                {
                    ExceptionHelper.ThrowSyntaxError("Class must have name", state.Code, index);
                }
                if (state.Strict && state.FunctionScopeLevel != state.LexicalScopeLevel)
                {
                    ExceptionHelper.ThrowSyntaxError("In strict mode code, class can only be declared at top level or immediately within other function.", state.Code, index);
                }

                state.Variables.Add(result.reference._descriptor);
            }
            index = i + 1;
            return(result);
        }
Example #20
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            if (!Parser.Validate(state.Code, "with (", ref i) && !Parser.Validate(state.Code, "with(", ref i))
            {
                return(null);
            }
            if (state.Strict)
            {
                ExceptionHelper.Throw((new NiL.JS.BaseLibrary.SyntaxError("WithStatement is not allowed in strict mode.")));
            }

            if (state.Message != null)
            {
                state.Message(MessageLevel.CriticalWarning, index, 4, "Do not use \"with\".");
            }

            var obj = Parser.Parse(state, ref i, CodeFragmentType.Expression);

            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (state.Code[i] != ')')
            {
                ExceptionHelper.Throw((new NiL.JS.BaseLibrary.SyntaxError("Invalid syntax WithStatement.")));
            }
            do
            {
                i++;
            }while (Tools.IsWhiteSpace(state.Code[i]));

            CodeNode body = null;

            VariableDescriptor[] vars = null;
            var oldVariablesCount     = state.Variables.Count;

            state.LexicalScopeLevel++;
            using (state.WithCodeContext(CodeContext.InWith))
            {
                try
                {
                    body = Parser.Parse(state, ref i, 0);
                    vars = CodeBlock.extractVariables(state, oldVariablesCount);
                    body = new CodeBlock(new[] { body })
                    {
                        _variables = vars,
                        Position   = body.Position,
                        Length     = body.Length
                    };
                }
                finally
                {
                    state.LexicalScopeLevel--;
                }
            }

            var pos = index;

            index = i;
            return(new With()
            {
                _scope = obj,
                _body = body,
                Position = pos,
                Length = index - pos
            });
        }
Example #21
0
        private static int Evaluate(string statement, ParseInfo info)
        {
            //Is it empty?
            if (statement.Length == 0)
            {
                return (int)FunctionUtils.Functions.U;
            }
            else if (statement[0] == '\'')//Is it a char literal? 'X'
            {
                if(statement.Length == 3)
                {
                    return (int)statement[1];
                }
                else
                {

                    return (int)FunctionUtils.Functions.U;
                }
            }
            if (statement.All(c => !char.IsWhiteSpace(c))) //Does it accidentally have a space in it? Ex: "112 3", "SHIFTL L"
            {
                //Test whether it is all A-Z (FUNC)
                if (statement.All(c => c >= 'A' && c <= 'Z'))
                {
                    return FunctionUtils.StringToOpCode(statement);
                }
                //Is it an integer?
                if (statement.All(c => c >= '0' && c <= '9'))
                {
                    int value;
                    bool couldParse = int.TryParse(statement, out value);
                    if (couldParse == true)
                    {
                        return value;
                    }
                    else
                    {
                        info.AddError(ParseInfo.ErrorCodes.sem_int_no_parse, "Integer " + statement + " could not be parsed.", false, (info.parse_index - statement.Length));
                        return (int)FunctionUtils.Functions.U;
                    }
                }
                else
                {
                    info.AddError(ParseInfo.ErrorCodes.sem_statement_not_valid_general, "Statement " + statement + " not valid.", false, (info.parse_index - statement.Length));
                    return (int)FunctionUtils.Functions.U;
                }
            }
            else
            {
                info.AddError(ParseInfo.ErrorCodes.syn_statement_contains_whitespace, "Statement " + statement + " contains whitespace could not be parsed.", false, (info.parse_index - statement.Length));
                return (int)FunctionUtils.Functions.U;
            }

            return (int)FunctionUtils.Functions.U;
        }
Example #22
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            if (state.Code[index] != '{')
            {
                throw new ArgumentException("Invalid JSON definition");
            }
            var flds = new Dictionary <string, Expression>();
            var computedProperties = new List <KeyValuePair <Expression, Expression> >();
            int i = index;

            while (state.Code[i] != '}')
            {
                i++;
                Tools.SkipSpaces(state.Code, ref i);
                int s = i;
                if (state.Code[i] == '}')
                {
                    break;
                }

                bool getOrSet = Parser.Validate(state.Code, "get", ref i) || Parser.Validate(state.Code, "set", ref i);
                Tools.SkipSpaces(state.Code, ref i);
                if (getOrSet && state.Code[i] == '(')  // function with name 'get' or 'set'
                {
                    getOrSet = false;
                    i        = s;
                }

                var asterisk = state.Code[i] == '*';
                Tools.SkipSpaces(state.Code, ref i);

                var async = false;
                if (!asterisk)
                {
                    async = Parser.Validate(state.Code, "async", ref i);
                    Tools.SkipSpaces(state.Code, ref i);
                }

                if (Parser.Validate(state.Code, "[", ref i))
                {
                    var name = ExpressionTree.Parse(state, ref i, false, false, false, true, false);
                    while (Tools.IsWhiteSpace(state.Code[i]))
                    {
                        i++;
                    }
                    if (state.Code[i] != ']')
                    {
                        ExceptionHelper.ThrowSyntaxError("Expected ']'", state.Code, i);
                    }
                    do
                    {
                        i++;
                    }while (Tools.IsWhiteSpace(state.Code[i]));

                    Tools.SkipSpaces(state.Code, ref i);
                    CodeNode initializer;
                    if (state.Code[i] == '(')
                    {
                        initializer = FunctionDefinition.Parse(state, ref i, asterisk ? FunctionKind.AnonymousGenerator : async ? FunctionKind.AsyncAnonymousFunction : FunctionKind.AnonymousFunction);
                    }
                    else
                    {
                        if (!Parser.Validate(state.Code, ":", ref i))
                        {
                            ExceptionHelper.ThrowSyntaxError(Strings.UnexpectedToken, state.Code, i);
                        }
                        initializer = ExpressionTree.Parse(state, ref i);
                    }

                    switch (state.Code[s])
                    {
                    case 'g':
                    {
                        computedProperties.Add(new KeyValuePair <Expression, Expression>(name, new PropertyPair((Expression)initializer, null)));
                        break;
                    }

                    case 's':
                    {
                        computedProperties.Add(new KeyValuePair <Expression, Expression>(name, new PropertyPair(null, (Expression)initializer)));
                        break;
                    }

                    default:
                    {
                        computedProperties.Add(new KeyValuePair <Expression, Expression>(name, (Expression)initializer));
                        break;
                    }
                    }
                }
                else if (getOrSet && state.Code[i] != ':')
                {
                    i = s;
                    var mode             = state.Code[i] == 's' ? FunctionKind.Setter : FunctionKind.Getter;
                    var propertyAccessor = FunctionDefinition.Parse(state, ref i, mode) as FunctionDefinition;
                    var accessorName     = propertyAccessor._name;
                    if (!flds.ContainsKey(accessorName))
                    {
                        var propertyPair = new PropertyPair
                                           (
                            mode == FunctionKind.Getter ? propertyAccessor : null,
                            mode == FunctionKind.Setter ? propertyAccessor : null
                                           );
                        flds.Add(accessorName, propertyPair);
                    }
                    else
                    {
                        var vle = flds[accessorName] as PropertyPair;

                        if (vle == null)
                        {
                            ExceptionHelper.ThrowSyntaxError("Try to define " + mode.ToString().ToLowerInvariant() + " for defined field", state.Code, s);
                        }

                        do
                        {
                            if (mode == FunctionKind.Getter)
                            {
                                if (vle.Getter == null)
                                {
                                    vle.Getter = propertyAccessor;
                                    break;
                                }
                            }
                            else
                            {
                                if (vle.Setter == null)
                                {
                                    vle.Setter = propertyAccessor;
                                    break;
                                }
                            }

                            ExceptionHelper.ThrowSyntaxError("Try to redefine " + mode.ToString().ToLowerInvariant() + " of " + propertyAccessor.Name, state.Code, s);
                        }while (false);
                    }
                }
                else
                {
                    if (asterisk)
                    {
                        do
                        {
                            i++;
                        }while (Tools.IsWhiteSpace(state.Code[i]));
                    }

                    i = s;
                    var fieldName = "";
                    if (Parser.ValidateName(state.Code, ref i, false, true, state.strict))
                    {
                        fieldName = Tools.Unescape(state.Code.Substring(s, i - s), state.strict);
                    }
                    else if (Parser.ValidateValue(state.Code, ref i))
                    {
                        if (state.Code[s] == '-')
                        {
                            ExceptionHelper.Throw(new SyntaxError("Invalid char \"-\" at " + CodeCoordinates.FromTextPosition(state.Code, s, 1)));
                        }
                        double d = 0.0;
                        int    n = s;
                        if (Tools.ParseNumber(state.Code, ref n, out d))
                        {
                            fieldName = Tools.DoubleToString(d);
                        }
                        else if (state.Code[s] == '\'' || state.Code[s] == '"')
                        {
                            fieldName = Tools.Unescape(state.Code.Substring(s + 1, i - s - 2), state.strict);
                        }
                        else if (flds.Count != 0)
                        {
                            ExceptionHelper.Throw((new SyntaxError("Invalid field name at " + CodeCoordinates.FromTextPosition(state.Code, s, i - s))));
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        return(null);
                    }

                    while (Tools.IsWhiteSpace(state.Code[i]))
                    {
                        i++;
                    }

                    Expression initializer = null;

                    if (state.Code[i] == '(')
                    {
                        i           = s;
                        initializer = FunctionDefinition.Parse(state, ref i, asterisk ? FunctionKind.MethodGenerator : async ? FunctionKind.AsyncMethod : FunctionKind.Method);
                    }
                    else
                    {
                        if (asterisk || async)
                        {
                            ExceptionHelper.ThrowSyntaxError("Unexpected token", state.Code, i);
                        }

                        if (state.Code[i] != ':' && state.Code[i] != ',' && state.Code[i] != '}')
                        {
                            ExceptionHelper.ThrowSyntaxError("Expected ',', ';' or '}'", state.Code, i);
                        }

                        Expression aei = null;
                        if (flds.TryGetValue(fieldName, out aei))
                        {
                            if (state.strict ? (!(aei is Constant) || (aei as Constant).value != JSValue.undefined) : aei is PropertyPair)
                            {
                                ExceptionHelper.ThrowSyntaxError("Try to redefine field \"" + fieldName + "\"", state.Code, s, i - s);
                            }

                            if (state.message != null)
                            {
                                state.message(MessageLevel.Warning, i, 0, "Duplicate key \"" + fieldName + "\"");
                            }
                        }

                        if (state.Code[i] == ',' || state.Code[i] == '}')
                        {
                            if (!Parser.ValidateName(fieldName, 0))
                            {
                                ExceptionHelper.ThrowSyntaxError("Invalid variable name", state.Code, i);
                            }

                            initializer = new Variable(fieldName, state.lexicalScopeLevel);
                        }
                        else
                        {
                            do
                            {
                                i++;
                            }while (Tools.IsWhiteSpace(state.Code[i]));
                            initializer = ExpressionTree.Parse(state, ref i, false, false);
                        }
                    }
                    flds[fieldName] = initializer;
                }

                while (Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }

                if ((state.Code[i] != ',') && (state.Code[i] != '}'))
                {
                    return(null);
                }
            }

            i++;
            var pos = index;

            index = i;
            return(new ObjectDefinition(flds, computedProperties.ToArray())
            {
                Position = pos,
                Length = index - pos
            });
        }
Example #23
0
        private static FSM_States LookupTable(FSM_States current_state, char current_char, ParseInfo info)
        {
            switch (current_state)
            {
                case FSM_States.START://START expects the start of a function name, integer, character literal, comma (for an implied U), whitespace, or explicit comment
                case FSM_States.WHITE_SPACE:
                case FSM_States.COMMA:
                    if(current_char >= '0' && current_char <= '9')
                    {
                        return FSM_States.INDEPENDANT_UNIT;
                    }
                    else if(current_char >= 'A' && current_char <= 'Z')
                    {
                        return FSM_States.INDEPENDANT_UNIT;
                    }
                    else if(current_char == '\'')
                    {
                        return FSM_States.CHAR_LIT_BEGIN;
                    }
                    else if(current_char == ',')
                    {
                        return FSM_States.COMMA;
                    }
                    else if(char.IsWhiteSpace(current_char))
                    {
                        return FSM_States.WHITE_SPACE;
                    }
                    else if (current_char == ';')
                    {
                        return FSM_States.EXPLICIT_COMMENT_START;
                    }
                    else if (current_state == FSM_States.COMMA || current_state == FSM_States.WHITE_SPACE && current_char == 'g')
                    {
                        //COMMA similar in all regards to START, except it also allows for the start of the goto sequence
                        return FSM_States.GOTO_G;
                    }
                    else
                    {
                        return FSM_States.LOOKUP_ERROR;
                    }
                case FSM_States.INDEPENDANT_UNIT://INDEPENDANT UNIT expects another independant unit, comma, whitespace, or explicit comment
                    if (current_char >= '0' && current_char <= '9')
                    {
                        return FSM_States.INDEPENDANT_UNIT;
                    }
                    else if (current_char >= 'A' && current_char <= 'Z')
                    {
                        return FSM_States.INDEPENDANT_UNIT;
                    }
                    else if (current_char == ',')
                    {
                        return FSM_States.COMMA;
                    }
                    else if(char.IsWhiteSpace(current_char))
                    {
                        return FSM_States.WHITE_SPACE;
                    }
                    else if (current_char == ';')
                    {
                        return FSM_States.EXPLICIT_COMMENT_START;
                    }
                    else
                    {
                        return FSM_States.LOOKUP_ERROR;
                    }
                case FSM_States.CHAR_LIT_BEGIN://APOS expects any character between ' ' - '~' except '\''
                    if (current_char == '\'')
                    {
                        info.AddError(ParseInfo.ErrorCodes.syn_char_lit_empty, "Empty character literal detected");
                        return FSM_States.LOOKUP_ERROR;
                    }

                    if(current_char == '\\')
                    {
                        return FSM_States.CHAR_LIT_ESC;
                    }
                    else if (current_char >= ' ' && current_char <= '~')
                    {
                        return FSM_States.CHAR_LIT_VALUE;
                    }
                    else if (char.IsWhiteSpace(current_char) && current_char != ' ')
                    {
                        return FSM_States.WHITE_SPACE;//White space which is not ' '
                    }
                    else
                    {
                        return FSM_States.LOOKUP_ERROR;
                    }
                case FSM_States.CHAR_LIT_ESC://ESC expects any of these characters: a,b,f,n,r,t,v,\,',"
                    switch (current_char)
                    {
                        case 'a':
                        case 'b':
                        case 'f':
                        case 'n':
                        case 'r':
                        case 't':
                        case 'v':
                        case '\\':
                        case '\'':
                        case '\"':
                            return FSM_States.CHAR_LIT_VALUE;
                        default:
                            info.AddError(ParseInfo.ErrorCodes.sem_char_lit_unsupported, "" + info.statement_accum + current_char + " is not a supported escaped character literal");
                            return FSM_States.CHAR_LIT_VALUE;
                    }
                case FSM_States.CHAR_LIT_VALUE://VALUE expects only '\''
                    if (current_char == '\'')
                    {
                        return FSM_States.CHAR_LIT_END;
                    }
                    else
                    {
                        info.AddError(ParseInfo.ErrorCodes.syn_char_lit_bad_format, "Character literal " + info.statement_accum + current_char + " incorrectly formated.");
                        return FSM_States.LOOKUP_ERROR;
                    }
                case FSM_States.CHAR_LIT_END://Expects whitepace or a comma or
                    if (current_char == ',')
                    {
                        return FSM_States.COMMA;
                    }
                    else if (char.IsWhiteSpace(current_char))
                    {
                        return FSM_States.WHITE_SPACE;
                    }
                    else if (current_char == ';')
                    {
                        return FSM_States.EXPLICIT_COMMENT_START;
                    }
                    else
                    {
                        return FSM_States.LOOKUP_ERROR;
                    }
                case FSM_States.GOTO_G://GOTO_G expects O
                case FSM_States.GOTO_GO://expects t
                case FSM_States.GOTO_GOT://expects o
                case FSM_States.GOTO_GOTO://expects ' ' or ';'
                    char search_letter = '\0';
                    switch (current_state)
                    {
                        case FSM_States.GOTO_G:
                            search_letter = 'o';
                            break;
                        case FSM_States.GOTO_GO:
                            search_letter = 't';
                            break;
                        case FSM_States.GOTO_GOT:
                            search_letter = 'o';
                            break;
                        case FSM_States.GOTO_GOTO:
                            info.ClearAccumulator();//we can't evauluate the word goto
                            if (char.IsWhiteSpace(current_char) == true)
                            {
                                return FSM_States.WHITE_SPACE;
                            }
                            else if (current_char == ';')
                            {
                                return FSM_States.EXPLICIT_COMMENT_START;
                            }
                            else
                            {
                                info.AddError(ParseInfo.ErrorCodes.syn_goto_improperly_formed, "goto improperly formed");
                                return FSM_States.LOOKUP_ERROR;
                            }
                            break;
                        default:
                            break;
                    }
                    if (current_char == search_letter)
                    {
                        return current_state + 1;
                    }
                    else
                    {
                        info.AddError(ParseInfo.ErrorCodes.syn_goto_improperly_formed,"goto improperly formed");
                        return FSM_States.LOOKUP_ERROR;
                    }
                case FSM_States.END:
                case FSM_States.LOOKUP_ERROR:
                default:
                    break;
            }

            return FSM_States.LOOKUP_ERROR;
        }
Example #24
0
 private AJPHelper.Operation Start(ParseInfo info)
 {
     ThreadPool.QueueUserWorkItem(Callback, info);
     return(info.Operation);
 }
Example #25
0
        /// <summary>
        /// Parses a line of code and produces evaluated code and information
        /// </summary>
        /// <param name="source_line">The source_code line (without ending in a new line).</param>
        /// <param name="source_line_number">.</param>
        /// <returns></returns>
        public static OutputInfo ParseLine(string source_line, int source_line_number)
        {
            ParseInfo parse_info = new ParseInfo(source_line, source_line_number);

            //Set default values
            parse_info.out_info.op_code =       (int)FunctionUtils.Functions.NOP;
            parse_info.out_info.arg1 =          (int)FunctionUtils.Functions.U;
            parse_info.out_info.arg2 =          (int)FunctionUtils.Functions.U;
            parse_info.out_info.jump_location = (int)FunctionUtils.Functions.N;

            if (parse_info.line.Length == 0)
            {
                return parse_info.out_info;
            }

            FSM_States currentState = FSM_States.START;
            while (currentState != FSM_States.END)
            {
                FSM_States transition = LookupTable(currentState, parse_info.CurrentCharacter, parse_info);
                if (transition != FSM_States.LOOKUP_ERROR)
                {
                    currentState = transition;
                    if (transition == FSM_States.COMMA)
                    {
                        parse_info.InsertCode(Evaluate(parse_info.statement_accum, parse_info));
                        parse_info.IncreaseCommaCounter();
                        parse_info.ClearAccumulator();
                    }
                    else if (transition == FSM_States.EXPLICIT_COMMENT_START)
                    {
                        //Try to evauluate what we were just accumulating
                        parse_info.InsertCode(Evaluate(parse_info.statement_accum, parse_info));
                        //If we've encountered a ; early we end parsing
                        currentState = FSM_States.END;
                        break;
                    }
                    else if (transition != FSM_States.WHITE_SPACE)
                    {
                        //Add anything that isn't white space (' ' doesn't count)
                        parse_info.AccumulateStatement(parse_info.CurrentCharacter);
                    }

                    //Keep parsing as long as we are not at the end of the string yet
                    if (parse_info.parse_index < parse_info.line.Length - 1)
                    {
                        parse_info.AdvanceIndex();
                    }
                    else
                    {
                        //Try to evauluate what we were just accumulating
                        parse_info.InsertCode(Evaluate(parse_info.statement_accum, parse_info));
                        currentState = FSM_States.END;
                    }
                }
                else
                {
                    break;
                }
            }

            return parse_info.out_info;
        }
Example #26
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            if (!Parser.Validate(state.Code, "import", ref index))
            {
                return(null);
            }

            Tools.SkipSpaces(state.Code, ref index);

            var result = new ImportStatement();

            var start = index;

            if (!Parser.ValidateString(state.Code, ref index, true))
            {
                var onlyDefault = false;
                if (Parser.ValidateName(state.Code, ref index))
                {
                    var defaultAlias = state.Code.Substring(start, index - start);
                    result._map.Add(new KeyValuePair <string, string>("", defaultAlias));

                    onlyDefault = true;
                    Tools.SkipSpaces(state.Code, ref index);
                    if (state.Code[index] == ',')
                    {
                        onlyDefault = false;
                        index++;
                        Tools.SkipSpaces(state.Code, ref index);
                    }
                }

                if (!onlyDefault)
                {
                    if (result._map.Count == 0 && state.Code[index] == '*')
                    {
                        index++;
                        Tools.SkipSpaces(state.Code, ref index);
                        var alias = parseAlias(state.Code, ref index);
                        if (alias == null)
                        {
                            ExceptionHelper.ThrowSyntaxError("Expected identifier", state.Code, index);
                        }
                        result._map.Add(new KeyValuePair <string, string>("*", alias));
                    }
                    else if (state.Code[index] == '{')
                    {
                        parseImportMap(result, state.Code, ref index);
                    }
                    else
                    {
                        ExceptionHelper.ThrowSyntaxError(Strings.UnexpectedToken, state.Code, index);
                    }
                }

                Tools.SkipSpaces(state.Code, ref index);

                if (!Parser.Validate(state.Code, "from", ref index))
                {
                    ExceptionHelper.ThrowSyntaxError("Expected 'from'", state.Code, index);
                }

                Tools.SkipSpaces(state.Code, ref index);

                start = index;

                if (!Parser.ValidateString(state.Code, ref index, true))
                {
                    ExceptionHelper.ThrowSyntaxError("Expected module name", state.Code, index);
                }
            }

            result._moduleName = Tools.Unescape(state.Code.Substring(start + 1, index - start - 2), false);

            return(result);
        }
Example #27
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            Tools.SkipSpaces(state.Code, ref i);

            if (!Parser.Validate(state.Code, "for(", ref i) &&
                (!Parser.Validate(state.Code, "for (", ref i)))
            {
                return(null);
            }

            Tools.SkipSpaces(state.Code, ref i);

            var result = new ForOf()
            {
                _labels = state.Labels.GetRange(state.Labels.Count - state.LabelsCount, state.LabelsCount).ToArray()
            };

            VariableDescriptor[] vars = null;
            var oldVariablesCount     = state.Variables.Count;

            state.lexicalScopeLevel++;
            try
            {
                var vStart = i;
                result._variable = VariableDefinition.Parse(state, ref i, true);
                if (result._variable == null)
                {
                    if (state.Code[i] == ';')
                    {
                        return(null);
                    }

                    Tools.SkipSpaces(state.Code, ref i);

                    int start = i;
                    if (!Parser.ValidateName(state.Code, ref i, state.strict))
                    {
                        return(null);
                    }

                    var varName = Tools.Unescape(state.Code.Substring(start, i - start), state.strict);
                    if (state.strict)
                    {
                        if (varName == "arguments" || varName == "eval")
                        {
                            ExceptionHelper.ThrowSyntaxError("Parameters name may not be \"arguments\" or \"eval\" in strict mode at ", state.Code, start, i - start);
                        }
                    }

                    result._variable = new Variable(varName, state.lexicalScopeLevel)
                    {
                        Position = start, Length = i - start, ScopeLevel = state.lexicalScopeLevel
                    };

                    Tools.SkipSpaces(state.Code, ref i);

                    if (state.Code[i] == '=')
                    {
                        Tools.SkipSpaces(state.Code, ref i);

                        var defVal = ExpressionTree.Parse(state, ref i, false, false, false, true, true);
                        if (defVal == null)
                        {
                            return(defVal);
                        }

                        Expression exp = new AssignmentOperatorCache(result._variable as Variable ?? (result._variable as VariableDefinition)._initializers[0] as Variable);
                        exp = new Assignment(exp, defVal)
                        {
                            Position = exp.Position,
                            Length   = defVal.EndPosition - exp.Position
                        };

                        if (result._variable == exp._left._left)
                        {
                            result._variable = exp;
                        }
                        else
                        {
                            (result._variable as VariableDefinition)._initializers[0] = exp;
                        }

                        Tools.SkipSpaces(state.Code, ref i);
                    }
                }

                if (!Parser.Validate(state.Code, "of", ref i))
                {
                    if (oldVariablesCount < state.Variables.Count)
                    {
                        state.Variables.RemoveRange(oldVariablesCount, state.Variables.Count - oldVariablesCount);
                    }

                    return(null);
                }

                state.LabelsCount = 0;
                Tools.SkipSpaces(state.Code, ref i);

                if (result._variable is VariableDefinition)
                {
                    if ((result._variable as VariableDefinition)._variables.Length > 1)
                    {
                        ExceptionHelper.ThrowSyntaxError("Too many variables in for-of loop", state.Code, i);
                    }
                }

                result._source = Parser.Parse(state, ref i, CodeFragmentType.Expression);
                Tools.SkipSpaces(state.Code, ref i);

                if (state.Code[i] != ')')
                {
                    ExceptionHelper.Throw((new SyntaxError("Expected \")\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }

                i++;
                state.AllowBreak.Push(true);
                state.AllowContinue.Push(true);
                result._body = Parser.Parse(state, ref i, 0);
                state.AllowBreak.Pop();
                state.AllowContinue.Pop();
                result.Position = index;
                result.Length   = i - index;
                index           = i;
                vars            = CodeBlock.extractVariables(state, oldVariablesCount);
            }
            finally
            {
                state.lexicalScopeLevel--;
            }

            return(new CodeBlock(new[] { result })
            {
                _variables = vars,
                Position = result.Position,
                Length = result.Length
            });
        }
 private HttpRequestDatagram(byte[] buffer, int offset, ParseInfo parseInfo)
     : base(buffer, offset, parseInfo.Length, parseInfo.Version, parseInfo.Header, parseInfo.Body)
 {
     Method = parseInfo.Method;
     Uri    = parseInfo.Uri;
 }
Example #29
0
 public LambdaContextHandler(ParseInfo parseInfo, LambdaParameter parameter)
 {
     ParseInfo  = parseInfo;
     _parameter = parameter;
 }
Example #30
0
 public void ParseParams(ParseInfo parameters)
 {
     // throw new NotImplementedException();
 }
Example #31
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            if (!Parser.Validate(state.Code, "try", ref i) || !Parser.IsIdentifierTerminator(state.Code[i]))
            {
                return(null);
            }
            while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (i >= state.Code.Length)
            {
                ExceptionHelper.Throw(new SyntaxError("Unexpected end of line."));
            }
            if (state.Code[i] != '{')
            {
                ExceptionHelper.Throw((new SyntaxError("Invalid try statement definition at " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
            }
            var b = CodeBlock.Parse(state, ref i);

            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            CodeNode cb    = null;
            string   exptn = null;

            if (Parser.Validate(state.Code, "catch (", ref i) || Parser.Validate(state.Code, "catch(", ref i))
            {
                Tools.SkipSpaces(state.Code, ref i);

                int s = i;
                if (!Parser.ValidateName(state.Code, ref i, state.strict))
                {
                    ExceptionHelper.Throw((new SyntaxError("Catch block must contain variable name " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }

                exptn = Tools.Unescape(state.Code.Substring(s, i - s), state.strict);
                if (state.strict)
                {
                    if (exptn == "arguments" || exptn == "eval")
                    {
                        ExceptionHelper.Throw((new SyntaxError("Varible name can not be \"arguments\" or \"eval\" in strict mode at " + CodeCoordinates.FromTextPosition(state.Code, s, i - s))));
                    }
                }

                Tools.SkipSpaces(state.Code, ref i);

                if (!Parser.Validate(state.Code, ")", ref i))
                {
                    ExceptionHelper.Throw((new SyntaxError("Expected \")\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }
                while (Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }
                if (state.Code[i] != '{')
                {
                    ExceptionHelper.Throw((new SyntaxError("Invalid catch block statement definition at " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }
                state.lexicalScopeLevel++;
                try
                {
                    cb = CodeBlock.Parse(state, ref i);
                }
                finally
                {
                    state.lexicalScopeLevel--;
                }
                while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }
            }
            CodeNode f = null;

            if (Parser.Validate(state.Code, "finally", i) && Parser.IsIdentifierTerminator(state.Code[i + 7]))
            {
                i += 7;
                while (Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }
                if (state.Code[i] != '{')
                {
                    ExceptionHelper.Throw((new SyntaxError("Invalid finally block statement definition at " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }
                f = CodeBlock.Parse(state, ref i);
            }
            if (cb == null && f == null)
            {
                ExceptionHelper.ThrowSyntaxError("try block must contain 'catch' or/and 'finally' block", state.Code, index);
            }

            var pos = index;

            index = i;
            return(new TryCatch()
            {
                body = (CodeBlock)b,
                catchBody = (CodeBlock)cb,
                finallyBody = (CodeBlock)f,
                catchVariableDesc = new VariableDescriptor(exptn, state.lexicalScopeLevel + 1),
                Position = pos,
                Length = index - pos
            });
        }
Example #32
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (!Parser.Validate(state.Code, "for(", ref i) && (!Parser.Validate(state.Code, "for (", ref i)))
            {
                return(null);
            }
            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            CodeNode init      = null;
            CodeNode body      = null;
            CodeNode condition = null;
            CodeNode post      = null;
            CodeNode result    = null;

            var labelsCount       = state.LabelsCount;
            var oldVariablesCount = state.Variables.Count;

            state.LabelsCount = 0;
            state.lexicalScopeLevel++;
            try
            {
                init = VariableDefinition.Parse(state, ref i, true);
                if (init == null)
                {
                    init = ExpressionTree.Parse(state, ref i, forForLoop: true);
                }
                if ((init is ExpressionTree) &&
                    (init as ExpressionTree).Type == OperationType.None &&
                    (init as ExpressionTree)._right == null)
                {
                    init = (init as ExpressionTree)._left;
                }
                if (state.Code[i] != ';')
                {
                    ExceptionHelper.Throw((new SyntaxError("Expected \";\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }
                do
                {
                    i++;
                }while (Tools.IsWhiteSpace(state.Code[i]));
                condition = state.Code[i] == ';' ? null as CodeNode : ExpressionTree.Parse(state, ref i, forForLoop: true);
                if (state.Code[i] != ';')
                {
                    ExceptionHelper.Throw((new SyntaxError("Expected \";\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }
                do
                {
                    i++;
                }while (Tools.IsWhiteSpace(state.Code[i]));
                post = state.Code[i] == ')' ? null as CodeNode : ExpressionTree.Parse(state, ref i, forForLoop: true);
                while (Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }
                if (state.Code[i] != ')')
                {
                    ExceptionHelper.Throw((new SyntaxError("Expected \";\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }

                i++;
                Tools.SkipSpaces(state.Code, ref i);

                state.AllowBreak.Push(true);
                state.AllowContinue.Push(true);
                try
                {
                    body = Parser.Parse(state, ref i, 0);
                    var vds = body as VariableDefinition;
                    if (vds != null)
                    {
                        if (vds.Kind >= VariableKind.ConstantInLexicalScope)
                        {
                            ExceptionHelper.ThrowSyntaxError("Block scope variables can not be declared in for-loop directly", state.Code, body.Position);
                        }

                        if (state.message != null)
                        {
                            state.message(MessageLevel.Warning, body.Position, body.Length, "Do not declare variables in for-loop directly");
                        }
                    }
                }
                finally
                {
                    state.AllowBreak.Pop();
                    state.AllowContinue.Pop();
                }

                int startPos = index;
                index = i;

                result = new For()
                {
                    _body        = body,
                    _condition   = condition,
                    _initializer = init,
                    _post        = post,
                    labels       = state.Labels.GetRange(state.Labels.Count - labelsCount, labelsCount).ToArray(),
                    Position     = startPos,
                    Length       = index - startPos
                };

                var vars = CodeBlock.extractVariables(state, oldVariablesCount);
                result = new CodeBlock(new[] { result })
                {
                    _variables = vars, Position = result.Position, Length = result.Length
                };
            }
            finally
            {
                state.lexicalScopeLevel--;
            }

            return(result);
        }
Example #33
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            if (!Parser.Validate(state.Code, "export", ref index))
            {
                return(null);
            }

            Tools.SkipSpaces(state.Code, ref index);

            var result   = new ExportStatement();
            var reexport = 0;

            if (Parser.Validate(state.Code, "*", ref index))
            {
                reexport = 1;
            }
            else if (Parser.Validate(state.Code, "default", ref index))
            {
                reexport = -1;
                result._map.Add(new KeyValuePair <string, Expression>("", (Expression)ExpressionTree.Parse(state, ref index)));
            }
            else if (state.Code[index] == '{')
            {
                parseExportMap(result, state, ref index);
            }
            else
            {
                reexport = -1;
                var definition =
                    VariableDefinition.Parse(state, ref index)
                    ?? ClassDefinition.Parse(state, ref index)
                    ?? FunctionDefinition.Parse(state, ref index, BaseLibrary.FunctionKind.Function);

                if (definition == null)
                {
                    ExceptionHelper.ThrowSyntaxError(Strings.UnexpectedToken, state.Code, index);
                }

                result._internalDefinition = definition;
            }

            Tools.SkipSpaces(state.Code, ref index);

            if (Parser.Validate(state.Code, "from", ref index))
            {
                if (reexport == -1)
                {
                    ExceptionHelper.ThrowSyntaxError("Reexport is not allowed with this syntax", state.Code, index - 4);
                }

                Tools.SkipSpaces(state.Code, ref index);

                var start = index;
                if (!Parser.ValidateString(state.Code, ref index, false))
                {
                    ExceptionHelper.ThrowSyntaxError("Expected module name", state.Code, index);
                }

                result._reexportSourceModuleName = Tools.Unescape(state.Code.Substring(start + 1, index - start - 2), false);
            }
            else if (reexport == 1)
            {
                ExceptionHelper.ThrowSyntaxError("Expected 'from'", state.Code, index);
            }

            return(result);
        }
Example #34
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            if (!Parser.Validate(state.Code, "switch (", ref i) && !Parser.Validate(state.Code, "switch(", ref i))
            {
                return(null);
            }

            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }

            var      body   = new List <CodeNode>();
            var      funcs  = new List <FunctionDefinition>();
            var      cases  = new List <SwitchCase>();
            CodeNode result = null;

            cases.Add(new SwitchCase()
            {
                index = int.MaxValue
            });
            state.AllowBreak.Push(true);
            var oldVariablesCount = state.Variables.Count;

            VariableDescriptor[] vars = null;
            state.lexicalScopeLevel++;
            try
            {
                var image = ExpressionTree.Parse(state, ref i);

                if (state.Code[i] != ')')
                {
                    ExceptionHelper.Throw((new SyntaxError("Expected \")\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }

                do
                {
                    i++;
                }while (Tools.IsWhiteSpace(state.Code[i]));

                if (state.Code[i] != '{')
                {
                    ExceptionHelper.Throw((new SyntaxError("Expected \"{\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }

                do
                {
                    i++;
                }while (Tools.IsWhiteSpace(state.Code[i]));

                while (state.Code[i] != '}')
                {
                    do
                    {
                        if (Parser.Validate(state.Code, "case", i) && Parser.IsIdentifierTerminator(state.Code[i + 4]))
                        {
                            i += 4;
                            while (Tools.IsWhiteSpace(state.Code[i]))
                            {
                                i++;
                            }
                            var sample = ExpressionTree.Parse(state, ref i);
                            if (state.Code[i] != ':')
                            {
                                ExceptionHelper.Throw((new SyntaxError("Expected \":\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                            }
                            i++;
                            cases.Add(new SwitchCase()
                            {
                                index = body.Count, statement = sample
                            });
                        }
                        else if (Parser.Validate(state.Code, "default", i) && Parser.IsIdentifierTerminator(state.Code[i + 7]))
                        {
                            i += 7;
                            while (Tools.IsWhiteSpace(state.Code[i]))
                            {
                                i++;
                            }
                            if (cases[0].index != int.MaxValue)
                            {
                                ExceptionHelper.Throw((new SyntaxError("Duplicate default case in switch at " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                            }
                            if (state.Code[i] != ':')
                            {
                                ExceptionHelper.Throw((new SyntaxError("Expected \":\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                            }
                            i++;
                            cases[0].index = body.Count;
                        }
                        else
                        {
                            break;
                        }
                        while (Tools.IsWhiteSpace(state.Code[i]) || (state.Code[i] == ';'))
                        {
                            i++;
                        }
                    } while (true);
                    if (cases.Count == 1 && cases[0].index == int.MaxValue)
                    {
                        ExceptionHelper.Throw((new SyntaxError("Switch statement must contain cases. " + CodeCoordinates.FromTextPosition(state.Code, index, 0))));
                    }

                    var t = Parser.Parse(state, ref i, 0);
                    if (t == null)
                    {
                        continue;
                    }

                    body.Add(t);
                    while (Tools.IsWhiteSpace(state.Code[i]) || (state.Code[i] == ';'))
                    {
                        i++;
                    }
                }
                state.AllowBreak.Pop();
                i++;
                var pos = index;
                index  = i;
                result = new Switch(body.ToArray())
                {
                    functions = funcs.ToArray(),
                    cases     = cases.ToArray(),
                    image     = image,
                    Position  = pos,
                    Length    = index - pos
                };
                vars = CodeBlock.extractVariables(state, oldVariablesCount);
            }
            finally
            {
                state.lexicalScopeLevel--;
            }

            return(new CodeBlock(new[] { result })
            {
                _variables = vars,
                Position = result.Position,
                Length = result.Length
            });
        }
Example #35
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            if (state.Code[index] != '[')
            {
                throw new ArgumentException("Syntax error. Expected '['");
            }
            do
            {
                i++;
            }while (Tools.IsWhiteSpace(state.Code[i]));
            var elms = new List <Expression>();

            while (state.Code[i] != ']')
            {
                var start  = i;
                var spread = Parser.Validate(state.Code, "...", ref i);
                if (state.Code[i] == ',')
                {
                    if (spread)
                    {
                        ExceptionHelper.ThrowSyntaxError("Expected expression", state.Code, i);
                    }
                    elms.Add(null);
                }
                else
                {
                    elms.Add((Expression)ExpressionTree.Parse(state, ref i, false, false));
                }
                if (spread)
                {
                    elms[elms.Count - 1] = new Spread(elms[elms.Count - 1])
                    {
                        Position = start, Length = i - start
                    }
                }
                ;
                while (Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }
                if (state.Code[i] == ',')
                {
                    do
                    {
                        i++;
                    }while (Tools.IsWhiteSpace(state.Code[i]));
                }
                else if (state.Code[i] != ']')
                {
                    ExceptionHelper.ThrowSyntaxError("Expected ']'", state.Code, i);
                }
            }
            i++;
            var pos = index;

            index = i;
            return(new ArrayDefinition()
            {
                elements = elms.ToArray(),
                Position = pos,
                Length = index - pos
            });
        }
Example #36
0
 public void PushChild(ParseInfo info)
 {
     var parentInfo = this;
     if (parentInfo.current != null)
     {
       parentInfo.current = new QNode(parentInfo.current.Value, parentInfo.current.Nodes.Concat(info.allElements).ToArray());
     }
     else
     {
       parentInfo.prevElements = parentInfo.allElements.Concat(info.allElements).ToList();
     }
 }
Example #37
0
        private Func <Task <(Action on, Action off, object value)> > ParseLayoutView(Type type,
                                                                                     XNodeInfo xinfo, PageObject page, ParseInfo parseInfo)
        {
            Log.Information("PARSE ELEMENT {name} as ILayoutController", xinfo.Name);

            var createObject = CreateInstance(xinfo, type, out ParseInfo createInfo);

            var pinfo = parseInfo.Merge(createInfo);

            Func <Layout <View>, Task <(Action on, Action off)> > createElement = (layout) => DefaultTask2Action;

            foreach (var child in xinfo.Elements.Value)
            {
                var res       = ParseElement(child, page, pinfo);
                var locCreate = createElement;

                createElement = async(layout) =>
                {
                    var res1 = await locCreate.Invoke(layout);

                    var res2 = await res.Invoke( );

                    if (res2.value != null)
                    {
                        layout.Children.Add(res2.value as View);
                    }

                    return(JoinAction(res1.on, res2.on), JoinAction(res1.off, res2.off));
                };
            }

            var createProperty = ParseElementProperty(xinfo, page, type, pinfo);

            return(async( ) =>
            {
                var layout = createObject( ) as Layout <View>;

                var res1 = await createProperty(layout);

                var res2 = await createElement(layout);

                return (JoinAction(res1.on, res2.on), JoinAction(res1.off, res2.off), layout);
            });
        }
Example #38
0
 private HttpRequestDatagram(byte[] buffer, int offset, ParseInfo parseInfo)
     :base(buffer, offset, parseInfo.Length, parseInfo.Version, parseInfo.Header, parseInfo.Body)
 {
     Method = parseInfo.Method;
     Uri = parseInfo.Uri;
 }
 public object Parse(ParseInfo parseInfo)
 {
     return((byte)(parseInfo.Data[0] & 0b00001111));
 }
 private HttpResponseDatagram(byte[] buffer, int offset, ParseInfo parseInfo)
     : base(buffer, offset, parseInfo.Length, parseInfo.Version, parseInfo.Header, parseInfo.Body)
 {
     StatusCode = parseInfo.StatusCode;
     ReasonPhrase = parseInfo.ReasonPhrase;
 }
Example #41
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            //string code = state.Code;
            int i = index;

            if (!Parser.Validate(state.Code, "while (", ref i) && !Parser.Validate(state.Code, "while(", ref i))
            {
                return(null);
            }
            int labelsCount = state.LabelsCount;

            state.LabelsCount = 0;
            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            var condition = Parser.Parse(state, ref i, CodeFragmentType.Expression);

            while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (i >= state.Code.Length)
            {
                ExceptionHelper.Throw(new SyntaxError("Unexpected end of line."));
            }
            if (state.Code[i] != ')')
            {
                throw new ArgumentException("code (" + i + ")");
            }
            do
            {
                i++;
            }while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]));
            if (i >= state.Code.Length)
            {
                ExceptionHelper.Throw(new SyntaxError("Unexpected end of line."));
            }
            state.AllowBreak.Push(true);
            state.AllowContinue.Push(true);
            int ccs  = state.continiesCount;
            int cbs  = state.breaksCount;
            var body = Parser.Parse(state, ref i, 0);

            if (body is FunctionDefinition)
            {
                if (state.strict)
                {
                    ExceptionHelper.Throw((new NiL.JS.BaseLibrary.SyntaxError("In strict mode code, functions can only be declared at top level or immediately within another function.")));
                }
                if (state.message != null)
                {
                    state.message(MessageLevel.CriticalWarning, CodeCoordinates.FromTextPosition(state.Code, body.Position, body.Length), "Do not declare function in nested blocks.");
                }
                body = new CodeBlock(new[] { body }); // для того, чтобы не дублировать код по декларации функции,
                // она оборачивается в блок, который сделает самовыпил на втором этапе, но перед этим корректно объявит функцию.
            }
            state.AllowBreak.Pop();
            state.AllowContinue.Pop();
            var pos = index;

            index = i;
            return(new While()
            {
                allowRemove = ccs == state.continiesCount && cbs == state.breaksCount,
                body = body,
                condition = condition,
                labels = state.Labels.GetRange(state.Labels.Count - labelsCount, labelsCount).ToArray(),
                Position = pos,
                Length = index - pos
            });
        }