Ejemplo n.º 1
0
        // 获取用户转账事务ID
        private IEnumerator GetUserTransferID(string transferFrom, string transferTo,
                                              TokenCode tokenCode, string amount)
        {
            FormData formData = new FormData()
                                .AddField("app_id", _appID)
                                .AddField("app_key", _appKey)
                                .AddField("transfer_from", transferFrom)
                                .AddField("transfer_to", transferTo)
                                .AddField("coin_code", ((int)tokenCode).ToString())
                                .AddField("coin_amount", amount);

            Request request = new Request(EOTAPI.TransferRequest).Post(RequestBody.From(formData));
            Client  http    = new Client();

            yield return(http.Send(request));

            if (http.IsSuccessful())
            {
                Response resp = http.Response();
                Debug.Log("TransferRequestResponse: " + resp.Body());

                _transferRequestResponse = JsonUtility.FromJson <TransferRequestResponse>(resp.Body());
            }
            else
            {
                Debug.LogError("NetWorkError: " + http.Error());
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Checks, if the last extracted token is the expected one.
 /// Throws exception, if not.
 /// </summary>
 /// <param name="tokenCode">An expected token code.</param>
 /// <param name="errorMessage">An error mesage thrown as an exception, if the expected token was not found.</param>
 private void Expect(TokenCode tokenCode, string errorMessage)
 {
     if (Tokenizer.CurrentToken.TokenCode != tokenCode)
     {
         throw new CompilerException(Tokenizer.CurrentLine, Tokenizer.CurrentLinePosition, errorMessage);
     }
 }
Ejemplo n.º 3
0
 public Terminal(string str_, int start_idx_, int final_idx_, TokenCode code_)
 {
     str       = str_;
     start_idx = start_idx_ + 1;
     final_idx = final_idx_ + 1;
     code      = code_;
 }
Ejemplo n.º 4
0
        private Token scanShortComment(Position begin)
        {
            // '//' sequence is already scanned.
            TokenCode code = TokenCode.SComment;
            char      ch   = reader.getChar();

            if (ch == '/')
            {
                reader.forgetChar(); code = TokenCode.DComment;
            }

            string comment = "//";

            while (true)
            {
                ch = reader.getChar();
                if (ch == '\n' || ch == '\0')
                {
                    break;
                }
                comment += ch;
                reader.forgetChar();
            }
            return(new Token(new Span(begin, reader.currPos()),
                             code, comment,
                             new Category(CategoryCode.trivia)));
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Create a new Token.
 /// </summary>
 /// <param name="lexeme">Lexeme is the basic unit of the lexicon.</param>
 /// <param name="code">The token code to the formed lexeme.</param>
 /// <param name="line">The line location of the token.</param>
 /// <param name="column">The column location of the token.</param>
 public Token(string lexeme, TokenCode code = TokenCode.Id, int line = 1, int column = 0)
 {
     Lexeme = lexeme;
     Code   = code;
     Line   = line;
     Column = column;
 }
Ejemplo n.º 6
0
        public static Token detectOperatorSign(Token token)
        {
            Span      span;
            string    image;
            TokenCode code = TokenCode.Identifier;

            switch (token.code)
            {
            case TokenCode.Assign:           //  :=
            case TokenCode.Equal:            //  =
            case TokenCode.EqualEqual:       //  ==
            case TokenCode.NotEqual:         //  /=
            case TokenCode.NotEqualDeep:     //  /==
            case TokenCode.Less:             //  <
            case TokenCode.LessEqual:        //  <=
            case TokenCode.Greater:          //  >
            case TokenCode.GreaterEqual:     //  >=
            case TokenCode.Tilde:            //  ~
            case TokenCode.Question:         //  ?
            case TokenCode.Vertical:         //  |
            case TokenCode.Caret:            //  ^
            case TokenCode.Plus:             //  +
            case TokenCode.Minus:            //  -
            case TokenCode.Multiply:         //  *
            case TokenCode.Divide:           //  /
            case TokenCode.Remainder:        //  %
            case TokenCode.Ampersand:        //  &
            // case TokenCode.Call:         //  ()
            case TokenCode.Power:            //  **
                forget();
                span  = new Span(token.span);
                image = token.image;
                break;

            // Additional (reserved) operator signs

            // case TokenCode.BackSlash:       //  \
            // case TokenCode.BackBackSlash:   //  \\
            // case TokenCode.DblArrow:        //  <=>
            // case TokenCode.PlusEqual:       //  +=
            // case TokenCode.MinusEqual:      //  -=
            // case ...

            case TokenCode.LParen:            //  (, and ) is expected after it
                forget();
                Token right = expect(TokenCode.RParen);
                span  = new Span(token.span, right.span);
                image = "()";
                break;

            default:
                // Not an operator sign
                span  = new Span(token.span);
                image = token.image;
                code  = TokenCode.ERROR;
                break;
            }
            return(new Token(span, code, image, new Category(CategoryCode.identifier)));
        }
Ejemplo n.º 7
0
        private static TokenCode getUnitKeyword()
        {
            Token     token = get();
            TokenCode code  = token.code;

            forget();
            return(code);
        }
Ejemplo n.º 8
0
 public Token(Span s, TokenCode c, string i, Category ct, object v = null)
 {
     span     = s;
     code     = c;
     image    = i;
     category = ct;
     value    = v;
 }
Ejemplo n.º 9
0
        private string RequireToken(TokenCode required)
        {
            var(token, value) = GetToken();
            if (token != required)
            {
                throw new InvalidOperationException($"Unexpected token {token}, {value}. Expected {required}");
            }

            return(value);
        }
Ejemplo n.º 10
0
        public static string GetLexeme(this TokenCode value)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());

            if (fieldInfo == null)
            {
                return(null);
            }
            var attribute = (LexemeAttribute)fieldInfo.GetCustomAttribute(typeof(LexemeAttribute));

            return(attribute.Text);
        }
Ejemplo n.º 11
0
        public static Token expect(TokenCode code)
        {
            Token token = get();

            if (token.code == code)
            {
                forget(); return(token);
            }
            // Else error: token 'code' expected but not found
            error(token, "not-found", code.ToString());
            return(null);
        }
Ejemplo n.º 12
0
        private string RequireAssignment(TokenCode required)
        {
            var token = PeekToken();

            if (token.Item1 != required)
            {
                return(null);
            }

            RequireToken(required);
            RequireToken(TokenCode.EQUAL);
            return(RequireToken(TokenCode.STRING));
        }
Ejemplo n.º 13
0
        private IEnumerable <string> RequireArray(TokenCode required)
        {
            var tok = PeekToken();

            if (tok.Item1 != required)
            {
                return(null);
            }

            RequireToken(required);
            RequireToken(TokenCode.EQUAL);
            RequireToken(TokenCode.LBRACKET);

            return(GetArrayValue());
        }
        private void Factor()
        {
            if (IsFactor(currentToken))
            {
                if (currentToken.Code.Equals(TokenCode.LeftParenthesis))
                {
                    NextToken();
                    Expression();

                    if (currentToken.Code.Equals(TokenCode.RightParenthesis))
                    {
                        NextToken();
                    }
                    else
                    {
                        SyntaxError(currentToken, TokenCode.RightParenthesis);
                    }
                }
                else if (IsFunctionCall(currentToken))
                {
                    FunctionCall();
                }
                else
                {
                    NextToken();
                }
            }
            else
            {
                TokenCode[] expected = new TokenCode[]
                {
                    TokenCode.True,
                    TokenCode.False,
                    TokenCode.Number,
                    TokenCode.Text,
                    TokenCode.Id,
                    TokenCode.Null,
                    TokenCode.LeftParenthesis
                };
                SyntaxError(currentToken, expected);
            }
        }
Ejemplo n.º 15
0
        private IDictionary <string, IEnumerable <string> > RequireDictionaryList(TokenCode required)
        {
            var tok = PeekToken();

            if (tok.Item1 != required)
            {
                return(null);
            }

            RequireToken(required);
            RequireToken(TokenCode.EQUAL);
            RequireToken(TokenCode.LCURLY);

            var result = new Dictionary <string, IEnumerable <string> >();

            for (; ;)
            {
                var(token, value) = GetToken();
                if (token == TokenCode.STRING)
                {
                    RequireToken(TokenCode.COLON);
                    var(token2, value2) = GetToken();
                    if (token2 != TokenCode.LBRACKET)
                    {
                        throw new InvalidOperationException($"Unexpected token {token2}, {value2}. Expected TokenCode.LBRACKET");
                    }

                    var val = GetArrayValue();

                    result.Add(value, val);
                    continue;
                }

                if (token == TokenCode.RCURLY)
                {
                    break;
                }
            }

            return(result);
        }
Ejemplo n.º 16
0
        private Token scanNumeric(int power, bool m = false)
        {
            string scale = "0123456789ABCDEF".Substring(0, power);

            Position begin        = reader.currPos();
            long     resultInt    = 0;
            double   resultDouble = 0.0;
            string   image        = "";

            while (true)
            {
                char curr = reader.getChar();
                if (curr == '_')
                {
                    reader.forgetChar(); continue;
                }
                int i = scale.IndexOf(curr);
                if (i == -1)
                {
                    break;
                }
                image += curr;
                reader.forgetChar();
                if (m)
                {
                    resultDouble = resultDouble + ((double)i) / power;
                    power       *= 10;
                }
                else
                {
                    resultInt = resultInt * power + i;
                }
            }
            object    resValue = m ? (object)resultDouble : (object)resultInt;
            TokenCode code     = m ? TokenCode.Real : TokenCode.Integer;

            return(new Token(new Span(begin, reader.currPos()),
                             code, image,
                             new Category(CategoryCode.literal),
                             resValue));
        }
        private void Write()
        {
            if (currentToken.Code.Equals(TokenCode.Write))
            {
                NextToken();
            }
            else
            {
                SyntaxError(currentToken, TokenCode.Write);
            }

            if (IsExpression(currentToken))
            {
                Expression();
            }
            else // Revisar
            {
                TokenCode[] expected = new TokenCode[]
                {
                    TokenCode.And
                };
                SyntaxError(currentToken, expected);
            }
        }
Ejemplo n.º 18
0
 public Token( TokenCode c, Position b )
 {
     code = c;
     begin = b;
     end = new Position(b.number,b.position+1);
 }
Ejemplo n.º 19
0
 public Token skipUntil(TokenCode stop)
 {
     Token token;
     while (true)
     {
         token = getToken();
         if ( token.code == stop ) break;
         if ( token.code == TokenCode.EOF ) errors.fatal(token,10);
         forget();
     }
     current = token;
     return token;
 }
Ejemplo n.º 20
0
 public Token(TokenCode code)
     : this()
 {
     this.Code = code;
 }
Ejemplo n.º 21
0
        protected bool TokenIn(TokenCode tokenCode, TokenCode[] tokenList)
        {
            if (tokenList != null)
            {
                foreach (TokenCode code in tokenList)
                {
                    if (tokenCode == code)
                        return true;
                }
            }

            return false;
        }
Ejemplo n.º 22
0
 internal TokenBase(TokenCode tc)
 {
     Code = tc;
 }
        private void Statement()
        {
            if (IsIf(currentToken))
            {
                If();
            }
            else if (IsFor(currentToken))
            {
                For();
            }
            else if (IsAttribuition(currentToken))
            {
                Attribuition();
            }
            else if (IsFunctionCall(currentToken))
            {
                FunctionCall();

                if (currentToken.Code == TokenCode.Semicolon)
                {
                    NextToken();
                }
                else
                {
                    SyntaxError(currentToken, TokenCode.Semicolon);
                }
            }
            else if (IsIncrement(currentToken))
            {
                Increment();

                if (currentToken.Code == TokenCode.Semicolon)
                {
                    NextToken();
                }
                else
                {
                    SyntaxError(currentToken, TokenCode.Semicolon);
                }
            }
            else if (IsDecrement(currentToken))
            {
                Decrement();

                if (currentToken.Code == TokenCode.Semicolon)
                {
                    NextToken();
                }
                else
                {
                    SyntaxError(currentToken, TokenCode.Semicolon);
                }
            }
            else if (IsReturn(currentToken))
            {
                Return();

                if (currentToken.Code == TokenCode.Semicolon)
                {
                    NextToken();
                }
                else
                {
                    SyntaxError(currentToken, TokenCode.Semicolon);
                }
            }
            else if (IsRead(currentToken))
            {
                Read();

                if (currentToken.Code == TokenCode.Semicolon)
                {
                    NextToken();
                }
                else
                {
                    SyntaxError(currentToken, TokenCode.Semicolon);
                }
            }
            else if (IsWrite(currentToken))
            {
                Write();

                if (currentToken.Code == TokenCode.Semicolon)
                {
                    NextToken();
                }
                else
                {
                    SyntaxError(currentToken, TokenCode.Semicolon);
                }
            }
            else if (currentToken.Code.Equals(TokenCode.Break))
            {
                NextToken();

                if (currentToken.Code.Equals(TokenCode.Semicolon))
                {
                    NextToken();
                }
                else
                {
                    SyntaxError(currentToken, TokenCode.Semicolon);
                }
            }
            else
            {
                TokenCode[] expected = new TokenCode[]
                {
                    TokenCode.If,
                    TokenCode.For,
                    TokenCode.Id,
                    TokenCode.Return,
                    TokenCode.Read,
                    TokenCode.Write,
                    TokenCode.Break
                };
                SyntaxError(currentToken, expected);
            }
        }
Ejemplo n.º 24
0
 protected void CondGetTokenAppend(TokenCode tokenCode, ErrorCode errorCode)
 {
     //--Get another token only if the current one matches tokenCode.
     if (CurrentCode == tokenCode) GetTokenAppend();
     else Error(errorCode);  // error if no match
 }
Ejemplo n.º 25
0
        // 确认交易
        public IEnumerator Transfer(string transferFrom, string transferTo, TokenCode tokenCode, string amount)
        {
            yield return(GetUserTransferID(transferFrom, transferTo, tokenCode, amount));

            if (_transferRequestResponse == null)
            {
                UserTransferResult.Code = EOTConstant.CODE_NETWORK_ERROR;
                UserTransferResult.Msg  = EOTConstant.MSG_NETWORK_ERROR;

                Debug.LogError("TransferRequestResponse is null!!!");

                yield break;
            }

            if (!_transferRequestResponse.success)
            {
                UserTransferResult.Code = _transferRequestResponse.code;
                UserTransferResult.Msg  = _transferRequestResponse.msg;

                Debug.LogError("Get user transfer id failed!!!");
                Debug.LogError("Code: " + _transferRequestResponse.code + " Msg: " + _transferRequestResponse.msg);

                yield break;
            }

            // 打开浏览器,让用户自行验证
            string webURl = string.Format(EOTWeb.UserTransfer, _appID, _transferRequestResponse.transactionID,
                                          transferFrom, transferTo, (int)tokenCode, amount);

            Application.OpenURL(webURl);
            yield return(new WaitForSeconds(6.0f));

            _transferResultResponse = null;

            while (true)
            {
                yield return(GetUserTransferResult(transferFrom, transferTo, _transferRequestResponse.transactionID));

                if (_transferResultResponse == null)
                {
                    UserTransferResult.Code = EOTConstant.CODE_NETWORK_ERROR;
                    UserTransferResult.Msg  = EOTConstant.MSG_NETWORK_ERROR;
                    break;
                }

                if (!_transferResultResponse.success)
                {
                    UserTransferResult.Code = _transferResultResponse.code;
                    UserTransferResult.Msg  = _transferResultResponse.msg;
                    break;
                }

                if (_transferResultResponse.resultCode == ResultCode.SUCCESSFUL)
                {
                    UserTransferResult.Code          = EOTConstant.CODE_SUCCESS;
                    UserTransferResult.Msg           = EOTConstant.MSG_SUCCESS;
                    UserTransferResult.TransactionID = _transferRequestResponse.transactionID;
                    break;
                }

                yield return(new WaitForSeconds(1));
            }
        }
Ejemplo n.º 26
0
 public void SyntaxError(Token token, TokenCode expected)
 {
     throw new SyntaxErrorException(string.Format("Syntax error at line {0}, column {1}: The token {2} provided is invalid. Expected: {3}", token.Line, token.Column, token.Lexeme, expected.GetLexeme()));
 }
Ejemplo n.º 27
0
 public StringToken(TokenCode tokenCode, string s)
 {
     TokenCode   = tokenCode;
     StringValue = s ?? string.Empty;
 }
Ejemplo n.º 28
0
 public SimpleToken(TokenCode tokenCode)
 {
     TokenCode = tokenCode;
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Checks, if the last extracted token is the expected one.
 /// Throws an exception, if not, or moves to the next token, if it is.
 /// </summary>
 /// <param name="tokenCode">An expected token code.</param>
 /// <param name="errorMessage">An error mesage thrown as an exception, if the expected token was not found.</param>
 private void ExpectAndEat(TokenCode tokenCode, string errorMessage)
 {
     Expect(tokenCode, errorMessage);
     Eat();
 }
Ejemplo n.º 30
0
        /// <summary>
        ///
        /// </summary>
        /// <syntax>
        /// Объявление-контейнера
        ///         :   [ Спецификатор-контейнера ] unit Имя-контейнера [ FormalGenerics ]
        ///                 { Директива-контейнера }
        ///             is
        ///                 Тело-контейнера
        ///                 [ invariant Список-предикатов ]
        ///             end
        ///
        /// Спецификатор-контейнера
        ///         : ref | val | concurrent | abstract
        ///
        /// Имя-контейнера
        ///         : Составное-имя
        ///
        /// Директива-контейнера
        ///         : Директива-наследования
        ///         | Директива-использования
        ///
        /// Директива-наследования
        ///         : extend Базовый-контейнер { , Базовый-контейнер }
        ///
        /// Базовый-контейнер
        ///         : [ ~ ] UnitTypeName
        ///
        /// Тело-контейнера
        ///         : { Объявление }
        /// </syntax>
        /// <returns></returns>
        public static void parse(bool hidden, bool final, bool abstr, iSCOPE context)
        {
            Debug.Indent();
            Debug.WriteLine("Entering UNIT.parse");

            bool ref_val    = false;  // unit is reference by default
            bool concurrent = false;

            UNIT unit = null;

            Token token = get();
            Token begin = token;

            TokenCode code = TokenCode.Unit;

            switch (token.code)
            {
            case TokenCode.Ref:
                ref_val = true;
                forget();
                code = getUnitKeyword();
                break;

            case TokenCode.Val:
                ref_val = false;
                forget();
                code = getUnitKeyword();
                break;

            case TokenCode.Abstract:
                abstr = true;
                forget();
                code = getUnitKeyword();
                break;

            case TokenCode.Concurrent:
                concurrent = true;
                forget();
                code = getUnitKeyword();
                break;

            case TokenCode.Unit:
                code = TokenCode.Unit;
                forget();
                break;

            case TokenCode.Package:
                code = TokenCode.Package;
                forget();
                break;
            }

            // 1. Unit header

            token = expect(TokenCode.Identifier);
            Token compoundName = IDENTIFIER.parseCompoundName(token);

            if (code == TokenCode.Package)
            {
                if (!ENTITY.options.optConfig)
                {
                    warning(token, "no-config");
                    unit = new UNIT(compoundName.image, ref_val, abstr, concurrent);
                }
                else
                {
                    unit = new PACKAGE(compoundName.image, ref_val, abstr, concurrent);
                }
            }
            else
            {
                unit = new UNIT(compoundName.image, ref_val, abstr, concurrent);
            }

            Debug.WriteLine("======================" + compoundName.image);

            unit.parent = context.self;
            unit.setSpecs(hidden, final);
            Context.enter(unit);

            // 2. Generic parameters

            token = get();
            if (token.code == TokenCode.LBracket)
            {
                forget();
                while (true)
                {
                    var generic = FORMAL_GENERIC.parse(unit);
                    unit.add(generic);

                    token = get();
                    switch (token.code)
                    {
                    case TokenCode.Comma:
                    case TokenCode.Semicolon: forget(); continue;

                    case TokenCode.RBracket:  forget(); goto Finish;

                    default: { /* Syntax error */ break; }
                    }
                }
Finish:
                ;
            }

            // Possible unit alias

            token = get();
            if (token.code == TokenCode.Alias)
            {
                forget();
                token      = expect(TokenCode.Identifier);
                unit.alias = new IDENTIFIER(token);
            }

            // 3. Unit directives: inheritance

            token = get();
            if (token.code == TokenCode.Extend)
            {
                forget();
                while (true)
                {
                    PARENT parent = PARENT.parse(unit);
                    if (parent == null) /* Syntax error */ break {
                        ;
                    }
                    unit.add(parent);

                    token = get();
                    switch (token.code)
                    {
                    case TokenCode.Comma:
                    case TokenCode.Semicolon:
                    case TokenCode.EOL:
                        forget();
                        continue;

                    default:
                        goto Use;
                    }
                }
            }
Ejemplo n.º 31
0
        /// <summary>
        /// Parse a statement list until the
        /// terminator token.
        /// </summary>
        /// <param name="terminator">The terminator.</param>
        private void ParseStatementList(TokenCode terminator)
        {
            //--Loop to parse statements and to check for and skip semicolons.
            do
            {
                ParseStatement();

                if (TokenIn(CurrentCode, StatementStartList))
                {
                    Error(ErrorCode.MissingSemicolon);
                }
                else while (CurrentCode == TokenCode.Semicolon) GetTokenAppend();
            } while ((CurrentCode != terminator) && (CurrentCode != TokenCode.EndOfFile));
        }
Ejemplo n.º 32
0
 public Token(TokenCode c, Position b, Position e, string i=null)
 {
     code = c;
     begin = b;
     end = e;
     image = i;
 }
Ejemplo n.º 33
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="v"></param>
 public LITERAL(object v, Span s, TokenCode c)
 {
     this.value = v;
     this.setSpan(s);
     this.code = c;
 }
Ejemplo n.º 34
0
        /// <summary>
        /// The function processes all kinds of statements including
        /// assignments, calls, and variable/constant declarations.
        /// </summary>
        /// <param name="context"></param>
        /// <returns>true, if any construct (a statement, or a simple declaration)
        /// was processed, and false otherwise.</returns>
        public static bool parse(iSCOPE context, TokenCode stop1, TokenCode stop2, TokenCode stop3)
        {
            Debug.Indent();
            Debug.WriteLine("Entering STATEMENT.parse");

            bool result = true;

            Token token = get();
            Token begin = token;

            if (token.code == stop1 && stop1 != TokenCode.ERROR)
            {
                goto Finish;
            }
            if (token.code == stop2 && stop2 != TokenCode.ERROR)
            {
                goto Finish;
            }
            if (token.code == stop3 && stop3 != TokenCode.ERROR)
            {
                goto Finish;
            }

            switch (token.code)
            {
            // case TokenCode.Pure: -- doesn't make any sense
            case TokenCode.Safe:
            case TokenCode.Routine:
                ROUTINE.parse(token, false, false, false, 0, context);
                break;

            case TokenCode.If:
                IF.parse(context);
                break;

            case TokenCode.While:
            case TokenCode.Loop:
                LOOP.parse(null, context);
                break;

            // Break
            //     : break [ Label ]
            //
            // Label
            //     : Identifier
            case TokenCode.Break:
                BREAK.parse(context);
                break;

            // Statement
            //     : ...
            //     | raise [ Expression ]
            case TokenCode.Raise:
                forget();
                RAISE.parse(token.span, context);
                break;

            // Statement
            //     : ...
            //     | check PredicatesList end
            //     | ...
            case TokenCode.Check:
                CHECK.parse(context);
                break;

            // Statement
            //     : ...
            //     | return [ Expression ]
            //     | ...
            case TokenCode.Return:
                forget();
                EXPRESSION expr = EXPRESSION.parse(null, context);    // can be null
                RETURN     ret  = new RETURN(expr);
                if (expr != null)
                {
                    expr.parent = ret;
                    ret.setSpan(begin.span, expr.span);
                }
                else
                {
                    ret.setSpan(begin);
                }

                context.add(ret);
                break;

            // Statement
            //     : ...
            //     | Try
            //     | ...
            //
            // Try
            //     : try { Statement } Catches [ Else ] end
            //
            // Catches
            //     : catch [ "(" [ Identifier ":" ] Type ")" ] { Statement }
            //
            // Else
            //     : else { Statement }
            case TokenCode.Try:
                TRY.parse(context);
                break;

            // Statement
            //     : ...
            //     | ? Identifier
            //     | ...
            //
            case TokenCode.Question:

                break;

            case TokenCode.Init:
                // Initializer call
                forget();
                Token start = token;

                DECLARATION init = Context.find(INITIALIZER.initName);
                EXPRESSION  initRef;
                if (init != null)
                {
                    initRef = new REFERENCE(init);
                }
                else
                {
                    initRef = new UNRESOLVED(context, new IDENTIFIER(INITIALIZER.initName));
                }

                CALL call = new CALL(initRef);
                token = expect(TokenCode.LParen);
                while (true)
                {
                    EXPRESSION argument = EXPRESSION.parse(null, context);
                    call.add(argument);
                    argument.parent = call;

                    token = get();
                    if (token.code == TokenCode.Comma)
                    {
                        forget(); continue;
                    }
                    break;
                }
                token = expect(TokenCode.RParen);
                call.setSpan(start.span, token.span);
                context.add(call);
                break;

            case TokenCode.Identifier:
            {
                // Several different cases:
                //   - a label in front of while/loop
                //   - a declaration
                //   - a statement

                forget();
                Token next = get();
                if (next.code == TokenCode.LParen)
                {
                    forget();
                    TokenCode codeAfter = saveTokensUntilRightParenth(next);
                    switch (codeAfter)
                    {
                    case TokenCode.Colon:
                    case TokenCode.Is:
                    // case TokenCode.Do:
                    case TokenCode.Arrow:
                        //This as a routine declaration!!
                        ROUTINE.parse(token, false, false, false, 0, context);
                        goto Weiter;
                    }
                }
                EXPRESSION attempt = EXPRESSION.parse(token, context);
                if (attempt is UNRESOLVED)
                {
                    // Might be a label or a declaration...
                    Token idd = new Token(attempt.span, TokenCode.Identifier,
                                          (attempt as UNRESOLVED).name.identifier,
                                          new Category(CategoryCode.identifier));
                    token = get();
                    switch (token.code)
                    {
                    case TokenCode.Is:
                    case TokenCode.Comma:
                        // This is definitely a declaration
                        forget();
                        VARIABLE.parse(false, false, false, false, idd, token, context);
                        goto Weiter;

                    case TokenCode.Colon:
                        forget();
                        Token token2 = get();
                        if (token2.code == TokenCode.While || token2.code == TokenCode.Loop)
                        {
                            // This is a real label! Don't 'forget()'.
                            LOOP.parse(idd, context);
                        }
                        else
                        {
                            // This is definitely a variable declaration.
                            // Don't forget()
                            VARIABLE.parse(false, false, false, false, idd, token, context);
                        }
                        goto Weiter;

                    default:
                        // Nothing to do; just going further
                        break;
                    }
                }
                // 'attempt' is something else: a call or the left part of an assignment
                token = get();
                if (token.code == TokenCode.Assign)
                {
                    forget();
                    EXPRESSION right = EXPRESSION.parse(null, context);
                    ASSIGNMENT res   = new ASSIGNMENT(attempt, right);
                    res.setSpan(attempt.span, right.span);
                    context.add(res);
                }
                else
                {
                    if (!(attempt is CALL))       // something's wrong
                    {
                        result = false;
                    }
                    context.add(attempt);
                }
Weiter:
                break;
            }

            case TokenCode.Const:
                // Something like
                //     const a is 5...
                // OR
                //     const is a, b, ... end
                forget(); token = get();
                if (token.code == TokenCode.Is)
                {
                    forget();
                    CONSTANT.parse(context);
                }
                else
                {
                    VARIABLE.parse(false, false, true, false, null, null, context);
                }
                break;

            default:
                // Something else, e.g., (a... or this...
                // Either a function call or an assignment.
                //
                //     this := ...
                //     (if cond then a else b).f ...
                //     ^

                EXPRESSION e = EXPRESSION.parse(null, context);
                if (e == null)
                {
                    // Either an error or just the end of statement sequence
                    result = false;
                    break;
                }
                token = get();
                if (token.code == TokenCode.Assign)
                {
                    forget();
                    EXPRESSION right      = EXPRESSION.parse(null, context);
                    ASSIGNMENT assignment = new ASSIGNMENT(e, right);
                    assignment.setSpan(e.span, right.span);
                    context.add(assignment);
                }
                else
                {
                    context.add(e);
                }
                break;
            }
Finish:
            Debug.WriteLine("Exiting STATEMENT.parse");
            Debug.Unindent();

            return(result);
        }
Ejemplo n.º 35
0
        public static void parse(TokenCode stop1, TokenCode stop2, TokenCode stop3, iSCOPE context)
        {
            Debug.Indent();
            Debug.WriteLine("Entering BODY.parse");

            Token token;
            Token start = get();

            while (true)
            {
                bool res = STATEMENT.parse(context, stop1, stop2, stop3);

                if (!res)
                {
                    // Neither a statement nor a simple declaration.
                    // Perhaps, a nested/local function?
                    token = get();
                    switch (token.code)
                    {
                    case TokenCode.Routine:
                    case TokenCode.Safe:
                    case TokenCode.Pure:
                        forget();
                        int pure_safe = 0;
                        switch (token.code)
                        {
                        case TokenCode.Pure: pure_safe = 1; break;

                        case TokenCode.Safe: pure_safe = 2; break;
                        }
                        ROUTINE.parse(null, false, false, false, pure_safe, context);
                        break;

                    case TokenCode.Unit:
                    case TokenCode.Ref:
                    case TokenCode.Val:
                        // A _local_ unit???
                        UNIT.parse(context);
                        break;

                    default:
                        // What's this?
                        break;
                    }
                }

                token = get();
                if (token.code == TokenCode.Semicolon /*|| wasEOL*/)
                {
                    forget();
                }
                if (token.code == stop1)
                {
                    break;                        // don't 'forget()'
                }
                if (stop2 != TokenCode.ERROR && token.code == stop2)
                {
                    break;                                                    // don't 'forget()'
                }
                if (stop3 != TokenCode.ERROR && token.code == stop3)
                {
                    break;                                                    // don't 'forget()'
                }
            }

            BODY body = context as BODY;

            if (body == null) /* A system error */ } {