Exemplo n.º 1
0
        // [34] PrimaryExpression = Ident | Number | String | '(' Expression ')'.
        private bool IsPrimaryExpression(out PrimaryExpression primaryExpression)
        {
            primaryExpression = new PrimaryExpression();
            if (CheckToken(SyntaxKind.IdentifierToken))
            {
                return(true);
            }
            else if (CheckToken(SyntaxKind.NumberToken))
            {
                return(true);
            }
            else if (CheckToken(SyntaxKind.StringToken))
            {
                return(true);
            }
            else if (CheckToken(SyntaxKind.OpenBraceToken))
            {
                if (!IsExpression(out var expression))
                {
                    return(false);
                }
                if (!CheckToken(SyntaxKind.ClosingBraceToken))
                {
                    return(false);
                }

                return(true);
            }

            return(false);
        }
Exemplo n.º 2
0
        private void AnalysePrimaryExpression(PrimaryExpression expression, string type)
        {
            if (expression is IdentifierPE)
            {
                IdentifierPE identifierPe = (IdentifierPE)expression;
                variableExists(identifierPe);
                CheckType(type, identifierPe);
                return;
            }

            if (expression is BracketsPE)
            {
                BracketsPE bracketsPe = (BracketsPE)expression;
                AnalysePrimaryExpression(bracketsPe.GetExpression.getP1, type);
                AnalysePrimaryExpression(bracketsPe.GetExpression.getP2, type);
                AnalyzeOperator(bracketsPe.GetExpression.GetOperator(), type);
                return;
            }

            if (expression is ConditionPE)
            {
                ConditionPE conditionPe = (ConditionPE)expression;
                variableExists(conditionPe);
                if (type != "boolean")
                {
                    logCError(expression, "Boolean illegal in: " + type + "");
                }
            }
        }
Exemplo n.º 3
0
 Expression parseExpression()
 {
     Expression ExpAST;
     PrimaryExpression P1 = parsePrimary();
     Operate O = parseOperator();
     PrimaryExpression P2 = parsePrimary();
     ExpAST = new Expression(P1, O, P2);
     return ExpAST;
 }
Exemplo n.º 4
0
        private bool CheckType(string type, PrimaryExpression primaryExpression)
        {
            if (primaryExpression is IdentifierPE)
            {
                IdentifierPE identifierPe = (IdentifierPE)primaryExpression;
                if (!table.ContainsKey(identifierPe.getName()))
                {
                    return(false);
                }
                if (table[identifierPe.getName()] == type)
                {
                    return(true);
                }

                string[] msg = { "expected: " + type, "given: " + table[identifierPe.getName()] };
                logCError(primaryExpression, msg);
                return(false);
            }

            if (primaryExpression is ConditionPE)
            {
                if (_compilerUtils.Types[type] == _boolean)
                {
                    return(true);
                }
                string[] msg = { "expected: " + type, "given: " + _compilerUtils.Syntax[_boolean] };
                logCError(primaryExpression, msg);
                return(false);
            }

            if (primaryExpression is LiteralString)
            {
                if (_compilerUtils.Types[type] == _string)
                {
                    return(true);
                }
                string[] msg = { "expected: " + type, "given: " + _compilerUtils.Syntax[_string] };
                logCError(primaryExpression, msg);
                return(false);
            }

            if (primaryExpression is LiteralInt)
            {
                if (_compilerUtils.Types[type] == _integer)
                {
                    return(true);
                }
                string[] msg = { "expected: " + type, "given: " + _compilerUtils.Syntax[_integer] };
                logCError(primaryExpression, msg);
                return(false);
            }
            logCError(primaryExpression, "Unknown error in CheckType");
            return(false);
        }
Exemplo n.º 5
0
        private bool variableExists(PrimaryExpression primaryExpression)
        {
            if (primaryExpression is IdentifierPE)
            {
                if (!table.ContainsKey(((IdentifierPE)primaryExpression).getName()))
                {
                    logCError(primaryExpression, "variable: \"" + ((IdentifierPE)primaryExpression).getName() + "\" not declared.");
                    return(false);
                }
                return(true);
            }

            if (primaryExpression is ConditionPE || primaryExpression is LiteralPE)
            {
                return(true);
            }

            return(false);
        }
		ISemantic E(PrimaryExpression x)
		{
			if (x is IdentifierExpression)
				return E((IdentifierExpression)x);

			else if (x is TemplateInstanceExpression)
				return E((TemplateInstanceExpression)x);

			else if (x is TokenExpression)
				return E((TokenExpression)x);

			else if (x is ArrayLiteralExpression)
				return E((ArrayLiteralExpression)x);

			else if (x is AssocArrayExpression)
				return E((AssocArrayExpression)x);

			else if (x is FunctionLiteral)
				return E((FunctionLiteral)x);

			else if (x is AssertExpression)
				return E((AssertExpression)x);

			else if (x is MixinExpression)
				return E((MixinExpression)x);

			else if (x is ImportExpression)
				return E((ImportExpression)x);

			else if (x is TypeDeclarationExpression) // should be containing a typeof() only; static properties etc. are parsed as access expressions
				return E((TypeDeclarationExpression)x);

			else if (x is TypeidExpression)
				return E((TypeidExpression)x);

			else if (x is IsExpression)
				return E((IsExpression)x);

			else if (x is TraitsExpression)
				return E((TraitsExpression)x);

			return null;
		}
Exemplo n.º 7
0
 public object VisitPrimaryExpression(PrimaryExpression primaryExpression, object o)
 {
     primaryExpression.Expression.Visit(this);
     return(null);
 }
Exemplo n.º 8
0
        /// <summary>
        /// The following are rules for C expressions.
        /// </summary>
        public static void SetExpressionRules()
        {
            // expression
            //   : assignment-expression [ ',' assignment-expression ]*
            Expression.Is(
                AssignmentExpression
                .OneOrMore(Comma)
                .Then(exprs => {
                if (exprs.Count == 1)
                {
                    return(exprs[0]);
                }
                return(AssignmentList.Create(exprs));
            })
                );

            // primary-expression
            //   : identifier          # Cannot be a typedef name.
            //   | constant
            //   | string-literal
            //   | '(' expression ')'
            PrimaryExpression.Is(
                Either(Variable)
                .Or(Constant)
                .Or(StringLiteral)
                .Or(
                    (LeftParen).Then(Expression).Then(RightParen)
                    )
                );

            // An identifier for a variable must not be defined as a typedef name.
            Variable.Is(
                Identifier.Check(result => !result.Environment.IsTypedefName(result.Result)).Then(AST.Variable.Create)
                );

            // constant
            //   : const-char
            //   : const-int
            //   : const-float
            Constant.Is(
                Either(ConstChar)
                .Or(ConstInt)
                .Or(ConstFloat)
                );


            // constant-expression
            //   : conditional-expression
            //
            // Note:
            // The size of an array should be a constant.
            // Note that the check is actually performed in semantic analysis.
            ConstantExpression.Is(
                ConditionalExpression
                );

            // conditional-expression
            //   : logical-or-expression [ '?' expression ':' conditional-expression ]?
            ConditionalExpression.Is(
                (LogicalOrExpression)
                .Then(
                    Given <Expr>()
                    .Then(Question)
                    .Then(Expression)
                    .Then(Colon)
                    .Then(ConditionalExpression)
                    .Then(AST.ConditionalExpression.Create)
                    .Optional()
                    )
                );

            // assignment-expression
            //   : unary-expression assignment-operator assignment-expression   # first-set = first-set(unary-expression)
            //   | conditional-expression                                       # first-set = first-set(cast-expression) = first-set(unary-expression) ++ { '(' }
            //
            // Note:
            //   Assignment operators are:
            //     '=', '*=', '/=', '%=', '+=', '-=', '<<=', '>>=', '&=', '^=', '|='
            AssignmentExpression.Is(
                Either(
                    AssignmentOperator(
                        UnaryExpression,
                        AssignmentExpression,
                        BinaryOperatorBuilder.Create(Assign, Assignment.Create),
                        BinaryOperatorBuilder.Create(MultAssign, AST.MultAssign.Create),
                        BinaryOperatorBuilder.Create(DivAssign, AST.DivAssign.Create),
                        BinaryOperatorBuilder.Create(ModAssign, AST.ModAssign.Create),
                        BinaryOperatorBuilder.Create(AddAssign, AST.AddAssign.Create),
                        BinaryOperatorBuilder.Create(SubAssign, AST.SubAssign.Create),
                        BinaryOperatorBuilder.Create(LeftShiftAssign, LShiftAssign.Create),
                        BinaryOperatorBuilder.Create(RightShiftAssign, RShiftAssign.Create),
                        BinaryOperatorBuilder.Create(BitwiseAndAssign, AST.BitwiseAndAssign.Create),
                        BinaryOperatorBuilder.Create(XorAssign, AST.XorAssign.Create),
                        BinaryOperatorBuilder.Create(BitwiseOrAssign, AST.BitwiseOrAssign.Create)
                        )
                    ).Or(
                    ConditionalExpression
                    )
                );

            // postfix-expression
            //   : primary-expression [
            //         '[' expression ']'                      # Get element from array
            //       | '(' [argument-expression-list]? ')'     # Function call
            //       | '.' identifier                          # Get member from struct/union
            //       | '->' identifier                         # Get member from struct/union
            //       | '++'                                    # Increment
            //       | '--'                                    # Decrement
            //     ]*
            PostfixExpression.Is(
                PrimaryExpression
                .Then(
                    Either(
                        Given <Expr>()
                        .Then(LeftBracket)
                        .Then(Expression)
                        .Then(RightBracket)
                        .Then((array, index) => Dereference.Create(AST.Add.Create(array, index)))
                        ).Or(
                        Given <Expr>()
                        .Then(LeftParen)
                        .Then(ArgumentExpressionList.Optional(ImmutableList <Expr> .Empty))
                        .Then(RightParen)
                        .Then(FuncCall.Create)
                        ).Or(
                        Given <Expr>()
                        .Then(Period)
                        .Then(Identifier)
                        .Then(Attribute.Create)
                        ).Or(
                        Given <Expr>()
                        .Then(RightArrow)
                        .Then(Identifier)
                        .Then((expr, member) => Attribute.Create(Dereference.Create(expr), member))
                        ).Or(
                        Given <Expr>()
                        .Then(Increment)
                        .Then(PostIncrement.Create)
                        ).Or(
                        Given <Expr>()
                        .Then(Decrement)
                        .Then(PostDecrement.Create)
                        ).ZeroOrMore()
                    )
                );

            // argument-expression-list
            //   : assignment-expression [ ',' assignment-expression ]*
            ArgumentExpressionList.Is(
                AssignmentExpression.OneOrMore(Comma)
                );

            // unary-expression
            //   : postfix-expression               # first-set = { id, const, string }
            //   | '++' unary-expression            # first-set = { '++' }
            //   | '--' unary-expression            # first-set = { '--' }
            //   | unary-operator cast-expression   # first-set = { '&', '*', '+', '-', '~', '!' }
            //   | 'sizeof' unary-expression        # first-set = { 'sizeof' }
            //   | 'sizeof' '(' Type-name ')'       # first-set = { 'sizeof' }
            //
            // Notes:
            // 1. unary-operator can be '&', '*', '+', '-', '~', '!'.
            // 2. The last two rules are ambiguous: you can't figure out whether the x in sizeof(x) is a typedef of a variable.
            //    I have a parser hack for this: add a parser environment to track all the typedefs.
            // 3. first_set = first_set(postfix-expression) + { '++', '--', '&', '*', '+', '-', '~', '!', 'sizeof' }
            //              = first_set(primary-expression) + { '++', '--', '&', '*', '+', '-', '~', '!', 'sizeof' }
            //              = { id, const, string, '++', '--', '&', '*', '+', '-', '~', '!', 'sizeof' }
            UnaryExpression.Is(
                Either(
                    PostfixExpression
                    ).Or(
                    (Increment).Then(UnaryExpression).Then(PreIncrement.Create)
                    ).Or(
                    (Decrement).Then(UnaryExpression).Then(PreDecrement.Create)
                    ).Or(
                    (BitwiseAnd).Then(CastExpression).Then(Reference.Create)
                    ).Or(
                    (Mult).Then(CastExpression).Then(Dereference.Create)
                    ).Or(
                    (Add).Then(CastExpression).Then(Positive.Create)
                    ).Or(
                    (Sub).Then(CastExpression).Then(Negative.Create)
                    ).Or(
                    (BitwiseNot).Then(CastExpression).Then(AST.BitwiseNot.Create)
                    ).Or(
                    (LogicalNot).Then(CastExpression).Then(AST.LogicalNot.Create)
                    ).Or(
                    (SizeOf).Then(UnaryExpression).Then(SizeofExpr.Create)
                    ).Or(
                    (SizeOf).Then(LeftParen).Then(TypeName).Then(RightParen).Then(SizeofType.Create)
                    )
                );

            // cast-expression
            //   : unary-expression                     # first-set = { id, const, string, '++', '--', '&', '*', '+', '-', '~', '!', 'sizeof' }
            //   | '(' type_name ')' cast-expression    # first-set = '('
            CastExpression.Is(
                Either(
                    UnaryExpression
                    ).Or(
                    (LeftParen).Then(TypeName).Then(RightParen).Then(CastExpression)
                    .Then(TypeCast.Create)
                    )
                );

            // multiplicative-expression
            //   : cast-expression [ [ '*' | '/' | '%' ] cast-expression ]*
            MultiplicativeExpression.Is(
                BinaryOperator(
                    CastExpression,
                    BinaryOperatorBuilder.Create(Mult, Multiply.Create),
                    BinaryOperatorBuilder.Create(Div, Divide.Create),
                    BinaryOperatorBuilder.Create(Mod, Modulo.Create)
                    )
                );

            // additive-expression
            //   : multiplicative-expression [ [ '+' | '-' ] multiplicative-expression ]*
            AdditiveExpression.Is(
                BinaryOperator(
                    MultiplicativeExpression,
                    BinaryOperatorBuilder.Create(Add, AST.Add.Create),
                    BinaryOperatorBuilder.Create(Sub, AST.Sub.Create)
                    )
                );

            // shift-expression
            //   : additive-expression [ [ '<<' | '>>' ] additive-expression ]*
            ShiftExpression.Is(
                BinaryOperator(
                    AdditiveExpression,
                    BinaryOperatorBuilder.Create(LeftShift, LShift.Create),
                    BinaryOperatorBuilder.Create(RightShift, RShift.Create)
                    )
                );

            // relational-expression
            //   : shift-expression [ [ '<' | '>' | '<=' | '>=' ] shift-expression ]*
            RelationalExpression.Is(
                BinaryOperator(
                    ShiftExpression,
                    BinaryOperatorBuilder.Create(Less, AST.Less.Create),
                    BinaryOperatorBuilder.Create(Greater, AST.Greater.Create),
                    BinaryOperatorBuilder.Create(LessEqual, LEqual.Create),
                    BinaryOperatorBuilder.Create(GreaterEqual, GEqual.Create)
                    )
                );

            // equality-expression
            //   : relational-expression [ [ '==' | '!=' ] relational-expression ]*
            EqualityExpression.Is(
                BinaryOperator(
                    RelationalExpression,
                    BinaryOperatorBuilder.Create(Equal, AST.Equal.Create),
                    BinaryOperatorBuilder.Create(NotEqual, AST.NotEqual.Create)
                    )
                );

            // and-expression
            //   : equality-expression [ '&' equality-expression ]*
            AndExpression.Is(
                BinaryOperator(
                    EqualityExpression,
                    BinaryOperatorBuilder.Create(BitwiseAnd, AST.BitwiseAnd.Create)
                    )
                );

            // exclusive-or-expression
            //   : and-expression [ '^' and-expression ]*
            ExclusiveOrExpression.Is(
                BinaryOperator(
                    AndExpression,
                    BinaryOperatorBuilder.Create(Xor, AST.Xor.Create)
                    )
                );

            // inclusive-or-expression
            //   : exclusive-or-expression [ '|' exclusive-or-expression ]*
            InclusiveOrExpression.Is(
                BinaryOperator(
                    ExclusiveOrExpression,
                    BinaryOperatorBuilder.Create(BitwiseOr, AST.BitwiseOr.Create)
                    )
                );

            // logical-and-expression
            //   : inclusive-or-expression [ '&&' inclusive-or-expression ]*
            LogicalAndExpression.Is(
                BinaryOperator(
                    InclusiveOrExpression,
                    BinaryOperatorBuilder.Create(LogicalAnd, AST.LogicalAnd.Create)
                    )
                );

            // logical-or-expression
            //   :logical-and-expression [ '||' logical-and-expression ]*
            LogicalOrExpression.Is(
                BinaryOperator(
                    LogicalAndExpression,
                    BinaryOperatorBuilder.Create(LogicalOr, AST.LogicalOr.Create)
                    )
                );
        }
 public override void ExplicitVisit(PrimaryExpression fragment)
 {
     _fragments.Add(fragment);
 }
Exemplo n.º 10
0
        public object visitPrimaryExpression(PrimaryExpression expr, object arg)
        {
            Type eType = (Type)expr.visit(this, null);

            return(eType);
        }
Exemplo n.º 11
0
 public Expression(int line, PrimaryExpression p1, Operator o, PrimaryExpression p2) : base(line)
 {
     O  = o;
     P1 = p1;
     P2 = p2;
 }
Exemplo n.º 12
0
        ISemantic E(PrimaryExpression x)
        {
            if (x is IdentifierExpression)
            {
                return(E((IdentifierExpression)x));
            }

            else if (x is TemplateInstanceExpression)
            {
                return(E((TemplateInstanceExpression)x));
            }

            else if (x is TokenExpression)
            {
                return(E((TokenExpression)x));
            }

            else if (x is ArrayLiteralExpression)
            {
                return(E((ArrayLiteralExpression)x));
            }

            else if (x is AssocArrayExpression)
            {
                return(E((AssocArrayExpression)x));
            }

            else if (x is FunctionLiteral)
            {
                return(E((FunctionLiteral)x));
            }

            else if (x is AssertExpression)
            {
                return(E((AssertExpression)x));
            }

            else if (x is MixinExpression)
            {
                return(E((MixinExpression)x));
            }

            else if (x is ImportExpression)
            {
                return(E((ImportExpression)x));
            }

            else if (x is TypeDeclarationExpression)             // should be containing a typeof() only; static properties etc. are parsed as access expressions
            {
                return(E((TypeDeclarationExpression)x));
            }

            else if (x is TypeidExpression)
            {
                return(E((TypeidExpression)x));
            }

            else if (x is IsExpression)
            {
                return(E((IsExpression)x));
            }

            else if (x is TraitsExpression)
            {
                return(E((TraitsExpression)x));
            }

            return(null);
        }
Exemplo n.º 13
0
 public IriExpression Datatype <TExpression>(PrimaryExpression <TExpression> literal) where TExpression : ISparqlExpression
 {
     return(Datatype(literal.Expression));
 }
Exemplo n.º 14
0
 private void GeneratePrimaryExpression(PrimaryExpression primaryExpression)
 {
     if (primaryExpression is VariableIdent)
     {
         var variableIdent = primaryExpression as VariableIdent;
         var variableBuilder = this.symbolTable[variableIdent.Name];
         il.Emit(OpCodes.Ldloc, variableBuilder);
     }
     else if (primaryExpression is VariableAssignment)
     {
         var variableAssignment = primaryExpression as VariableAssignment;
         var name = variableAssignment.Name;
         if (!this.symbolTable.ContainsKey(name))
             this.symbolTable[name] = this.il.DeclareLocal(typeof(int));
         GenerateExpression(variableAssignment.Expression);
         il.Emit(OpCodes.Stloc, this.symbolTable[name]);
     }
     else if (primaryExpression is VariablePostIncrement)
     {
         var postIncrement = primaryExpression as VariablePostIncrement;
         var variableBuilder = this.symbolTable[postIncrement.Name];
         il.Emit(OpCodes.Ldloc, variableBuilder);
         GenerateIncrementOrDecrement(variableBuilder, InDeCrementStatus.PostIncrement);
     }
     else if (primaryExpression is VariablePostDecrement)
     {
         var postDecrement = primaryExpression as VariablePostDecrement;
         var variableBuilder = this.symbolTable[postDecrement.Name];
         il.Emit(OpCodes.Ldloc, variableBuilder);
         GenerateIncrementOrDecrement(variableBuilder, InDeCrementStatus.PostDecrement);
     }
     else if (primaryExpression is VariablePreIncrement)
     {
         var preIncrement = primaryExpression as VariablePreIncrement;
         var variableBuilder = this.symbolTable[preIncrement.Name];
         il.Emit(OpCodes.Ldloc, variableBuilder);
         GenerateIncrementOrDecrement(variableBuilder, InDeCrementStatus.PreIncrement);
     }
     else if (primaryExpression is VariablePreDecrement)
     {
         var preDecrement = primaryExpression as VariablePreDecrement;
         var variableBuilder = this.symbolTable[preDecrement.Name];
         il.Emit(OpCodes.Ldloc, variableBuilder);
         GenerateIncrementOrDecrement(variableBuilder, InDeCrementStatus.PreDecrement);
     }
     else if (primaryExpression is LogicalNotExpression)
     {
         var logicalNotExpression = primaryExpression as LogicalNotExpression;
         GeneratePrimaryExpression(logicalNotExpression.PrimaryExpression);
         GenerateOperation(Operation.Not);
     }
     else if (primaryExpression is Number)
     {
         var number = primaryExpression as Number;
         il.Emit(OpCodes.Ldc_I4, number.Value);
     }
     else if (primaryExpression is PrintFunction)
     {
         var printFunction = primaryExpression as PrintFunction;
         GenerateExpression(printFunction.Expression);
         this.il.Emit(OpCodes.Call, typeof(Console).GetMethod(
             "WriteLine",
             new Type[] { typeof(int) }
         ));
     }
     else if (primaryExpression is ScanFunction)
     {
         this.il.Emit(OpCodes.Call, typeof(System.Console).GetMethod(
             "ReadLine",
             BindingFlags.Public | BindingFlags.Static,
             null,
             new System.Type[] { },
             null
         ));
         this.il.Emit(OpCodes.Call, typeof(int).GetMethod(
             "Parse",
             BindingFlags.Public | BindingFlags.Static,
             null,
             new Type[] { typeof(string) },
             null
         ));
     }
     else if (primaryExpression is ParenthesesExpression)
     {
         var parenthesesExpression = primaryExpression as ParenthesesExpression;
         GenerateExpression(parenthesesExpression.Expression);
     }
 }
Exemplo n.º 15
0
 public Expression(PrimaryExpression P1, Operate O, PrimaryExpression P2)
 {
     this.P1 = P1; this.O = O; this.P2 = P2;
 }
        /**
         * Returns the expression that may precede the <code>super</code>
         * keyword of an explicit <code>super</code> constructor call.
         * <p>
         * A returned expression states the type a called <code>super</code>
         * constructor belongs to. For most cases this is something like <code>
         * ACertainType.this.base(...)</code>
         *
         * @return  The expression that precedes the <code>super</code>
         *          keyword or <code>null</code> if there is no such expression. If
         *          <code>this</code> represents an explicit <code>this</code>
         *          constructor call this method always returns<code>null</code>.
         */
        public PrimaryExpression getSuperType()
        {
            if (mPrimaryExprTree == null)
            {
                return null;
            }
            if (mSuperTypeExpr == null)
            {
                mSuperTypeExpr = AST2Expression.resolvePrimaryExpression(
                        mPrimaryExprTree, getTokenRewriteStream());
            }

            return mSuperTypeExpr;
        }
Exemplo n.º 17
0
 public UnaryExpression(PrimaryExpression expression, bool isNegated)
 {
     this.expression = expression;
     this.isNegated  = isNegated;
 }
Exemplo n.º 18
0
 public object VisitPrimaryExpression(PrimaryExpression primaryExpression, object o)
 {
     return(primaryExpression.Expression.Visit(this));
 }
Exemplo n.º 19
0
 public static bool AsBool(this PrimaryExpression primaryExpression) => bool.Parse(primaryExpression.Value);
Exemplo n.º 20
0
 public static int AsInt(this PrimaryExpression primaryExpression) => int.Parse(primaryExpression.Value);
Exemplo n.º 21
0
 public static long AsLong(this PrimaryExpression primaryExpression) => long.Parse(primaryExpression.Value);
 public sealed override void ExplicitVisit(PrimaryExpression node)
 {
     base.ExplicitVisit(node);
 }
Exemplo n.º 23
0
 public void AddPrimaryExpression(PrimaryExpression expression)
 {
     expressions.Add(expression);
 }
Exemplo n.º 24
0
 public override void ExplicitVisit(PrimaryExpression node) { this.action(node); }