Exemple #1
0
        public IErrorReporter ErrorSlicingOnDereference()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    AllowDereference = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                Int64Literal rhs_value = IntLiteral.Create("80");
                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "foo", null,
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.UnitNameReference(),
                                       Block.CreateStatement(
                                           VariableDeclaration.CreateStatement("p",
                                                                               NameFactory.PointerNameReference(NameFactory.IObjectNameReference(TypeMutability.Reassignable)),
                                                                               Undef.Create()),
                                           // only with same type we have guarantee we won't use dereference as slicing tool, consider
                                           // x *Object ; (*x) = big_type_instance
                                           Assignment.CreateStatement(Dereference.Create(NameReference.Create("p")), rhs_value)
                                           )));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.TypeMismatch, rhs_value));
            }

            return(resolver);
        }
Exemple #2
0
        public IErrorReporter ErrorDereferencingValue()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    AllowDereference = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                Int64Literal value = Int64Literal.Create("3");
                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "foo", null,
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new[] {
                    Return.Create(Dereference.Create(value)),
                })));


                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.DereferencingValue, value));
            }

            return(resolver);
        }
Exemple #3
0
        public IErrorReporter ErrorAssigningToNonReassignableData()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    AllowDereference = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                IExpression assign = Assignment.CreateStatement(Dereference.Create(NameReference.Create("a")), NameReference.Create("b"));

                root_ns.AddBuilder(FunctionBuilder.Create("swap", "T", VarianceMode.None,
                                                          NameFactory.UnitNameReference(),
                                                          Block.CreateStatement(
                                                              assign
                                                              ))
                                   .Parameters(FunctionParameter.Create("a", NameFactory.ReferenceNameReference("T")),
                                               FunctionParameter.Create("b", NameFactory.ReferenceNameReference("T"))));


                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.AssigningToNonReassignableData, assign));
            }

            return(resolver);
        }
        private Dereference ParseDereference()
        {
            var t = NextToken();

            if (!t.IsOperator(Operator.Asterisk))
            {
                _stream.Previous();

                return(null);
            }

            var node = new Dereference(t);

            var reg = ParseRegister(false);

            if (reg != null)
            {
                node.AddChild(reg);
            }
            else
            {
                var id = ParseIdentifier();
                node.AddChild(id);
            }

            return(node);
        }
Exemple #5
0
        public void VisitFieldAccess(FieldAccess acc)
        {
            int         prec = SetPrecedence(PrecedenceFieldAccess);
            Dereference d    = acc.Structure as Dereference;

            if (d != null)
            {
                d.Expression.Accept(this);
                writer.Write("->{0}", acc.FieldName);
            }
            else
            {
                var scope = acc.Structure as ScopeResolution;
                if (scope != null)
                {
                    scope.Accept(this);
                    writer.Write("::{0}", acc.FieldName);
                }
                else
                {
                    acc.Structure.Accept(this);
                    writer.Write(".{0}", acc.FieldName);
                }
            }
            ResetPresedence(prec);
        }
Exemple #6
0
        public void CfDerefFieldAccess()
        {
            Identifier id1 = new Identifier("v1", PrimitiveType.Word32, null);
            Expression e = new Dereference(PrimitiveType.Pointer32, new FieldAccess(PrimitiveType.Word32, id1, "foo"));
            e.Accept(cf);

            Assert.AreEqual("*v1.foo", sw.ToString());
        }
Exemple #7
0
 public bool VisitDereference(Dereference dereference)
 {
     if (!IsExpressionValid(dereference.Expression))
     {
         return(false);
     }
     return(Typer.GetExpressionType(_context, _environment, dereference.Expression) != null);
 }
Exemple #8
0
        public void VisitDereference(Dereference deref)
        {
            int prec = SetPrecedence(PrecedenceDereference);

            writer.Write("*");
            deref.Expression.Accept(this);
            ResetPresedence(prec);
        }
        public Expression VisitPointer(Pointer ptr)
        {
            Expression e = c !;

            if (IsSegmentPointer(ptr))
            {
                if (mpSelectorToSegId.TryGetValue(c !.ToUInt16(), out Identifier segID))
                {
                    return(segID);
                }
                return(e);
            }
            else if (GlobalVars != null)
            {
                // Null pointer.
                if (c !.IsZero)
                {
                    var np = Address.Create(ptr, 0);
                    np.TypeVariable = c.TypeVariable;
                    np.DataType     = c.DataType;
                    return(np);
                }

                var addr = program.Platform.MakeAddressFromConstant(c, false);

                // An invalid pointer -- often used as sentinels in code.
                if (addr is null || !program.SegmentMap.IsValidAddress(addr))
                {
                    //$TODO: probably should emit a reinterpret_cast here.
                    e = new Cast(ptr, c)
                    {
                        TypeVariable = c.TypeVariable
                    };
                    if (dereferenced)
                    {
                        e = new Dereference(ptr.Pointee, e);
                    }
                    return(e);
                }

                var dt       = ptr.Pointee.ResolveAs <DataType>() !;
                var charType = MaybeCharType(dt);
                if (charType != null && IsPtrToReadonlySection(addr))
                {
                    PromoteToCString(c, charType);
                    var rdr = program.CreateImageReader(program.Architecture, addr);
                    return(rdr.ReadCString(charType, program.TextEncoding));
                }
                if (dereferenced &&
                    TryReadReal(addr, dt, out var cReal) &&
                    IsPtrToReadonlySection(addr))
                {
                    return(cReal);
                }
                e = RewriteGlobalFieldAccess(dt, c.ToInt32());
            }
            return(e);
        }
Exemple #10
0
        public void CfDerefFieldAccess()
        {
            Identifier id1 = new Identifier("v1", PrimitiveType.Word32, null);
            Expression e   = new Dereference(PrimitiveType.Pointer32, new FieldAccess(PrimitiveType.Word32, id1, "foo"));

            e.Accept(cf);

            Assert.AreEqual("*v1.foo", sw.ToString());
        }
Exemple #11
0
        public IType VisitDereference(Dereference dereference)
        {
            var expressionType = GetExpressionType(dereference.Expression);

            if (expressionType is PointerType expressionPointerType)
            {
                return(expressionPointerType.UnderlyingType);
            }

            _context.Error(
                dereference.Span,
                $"cannot dereference a non-pointer type \"{expressionType}\"");
            return(null);
        }
Exemple #12
0
        public void VisitDereference(DMASTDereference dereference)
        {
            var expr = DMExpression.Create(_dmObject, _proc, dereference.Expression, _inferredPath);

            if (dereference.Type == DMASTDereference.DereferenceType.Direct && !Dereference.DirectConvertable(expr, dereference))
            {
                if (expr.Path == null)
                {
                    throw new CompileErrorException(dereference.Location, $"Invalid property \"{dereference.Property}\"");
                }

                DMObject dmObject = DMObjectTree.GetDMObject(expr.Path.Value, false);
                if (dmObject == null)
                {
                    throw new CompileErrorException(dereference.Location, $"Type {expr.Path.Value} does not exist");
                }

                var property = dmObject.GetVariable(dereference.Property);
                if (property != null)
                {
                    Result = new Expressions.Dereference(dereference.Location, property.Type, expr, dereference.Conditional, dereference.Property);
                }
                else
                {
                    var globalId = dmObject.GetGlobalVariableId(dereference.Property);
                    if (globalId != null)
                    {
                        property = DMObjectTree.Globals[globalId.Value];
                        Result   = new Expressions.GlobalField(dereference.Location, property.Type, globalId.Value);
                    }
                }

                if (property == null)
                {
                    throw new CompileErrorException(dereference.Location, $"Invalid property \"{dereference.Property}\" on type {dmObject.Path}");
                }

                if ((property.Value?.ValType & DMValueType.Unimplemented) == DMValueType.Unimplemented && !DMCompiler.Settings.SuppressUnimplementedWarnings)
                {
                    DMCompiler.Warning(new CompilerWarning(dereference.Location, $"{dmObject.Path}.{dereference.Property} is not implemented and will have unexpected behavior"));
                }
            }
            else
            {
                Result = new Expressions.Dereference(dereference.Location, null, expr, dereference.Conditional, dereference.Property);
            }
        }
Exemple #13
0
        public void VisitMemberPointerSelector(MemberPointerSelector mps)
        {
            int         prec = SetPrecedence(PrecedenceMemberPointerSelector);
            Dereference d    = mps.BasePointer as Dereference;

            if (d != null)
            {
                d.Expression.Accept(this);
                writer.Write("->*");
            }
            else
            {
                mps.BasePointer.Accept(this);
                writer.Write(".*");
            }
            var old = forceParensIfSamePrecedence;

            forceParensIfSamePrecedence = true;
            mps.MemberPointer.Accept(this);
            forceParensIfSamePrecedence = old;
            ResetPresedence(prec);
        }
        /// <summary>
        /// Creates an "addressof" expression.
        /// </summary>
        /// <param name="dt">Datatype of expression</param>
        /// <param name="e">expression to take address of</param>
        /// <returns></returns>
        public Expression MkAddrOf(DataType dt, Expression e)
        {
            // &*ptr == ptr
            Dereference d = e as Dereference;

            if (d != null)
            {
                return(d.Expression);
            }

            // *&a[i] = a + i;
            // *&a[0] = a
            ArrayAccess acc = e as ArrayAccess;

            if (acc != null)
            {
                Constant index = acc.Index as Constant;
                if (index != null && index.ToInt32() == 0)
                {
                    return(acc.Array);
                }
            }
            return(new UnaryExpression(Operator.AddrOf, dt, e));
        }
Exemple #15
0
        public virtual Expression VisitDereference(Dereference deref)
        {
            var e = deref.Expression.Accept(this);

            return(new Dereference(deref.DataType, e));
        }
Exemple #16
0
 public BitRange VisitDereference(Dereference deref)
 {
     throw new NotImplementedException();
 }
Exemple #17
0
 public ValueSet VisitDereference(Dereference deref)
 {
     throw new NotImplementedException();
 }
Exemple #18
0
 public SlicerResult VisitDereference(Dereference deref, BackwardSlicerContext ctx)
 {
     throw new NotImplementedException();
 }
 public virtual Expression VisitDereference(Dereference deref)
 {
     deref.Expression = deref.Expression.Accept(this);
     return(deref);
 }
		public virtual void VisitDereference(Dereference deref)
		{
			deref.Expression.Accept(this);
		}
Exemple #21
0
 public override void VisitDereference(Dereference deref)
 {
     deref.Expression.Accept(this);
     EnsureTypeVariable(deref);
 }
        public Expression VisitPointer(Pointer ptr)
        {
            Expression e = c;

            if (IsSegmentPointer(ptr))
            {
                Identifier segID;
                if (mpSelectorToSegId.TryGetValue(c.ToUInt16(), out segID))
                {
                    return(segID);
                }
                return(e);
            }
            else if (GlobalVars != null)
            {
                // Null pointer.
                if (c.IsZero)
                {
                    var np = Address.Create(ptr, 0);
                    np.TypeVariable = c.TypeVariable;
                    np.DataType     = c.DataType;
                    return(np);
                }

                var addr = program.Platform.MakeAddressFromConstant(c, false);
                // An invalid pointer -- often used as sentinels in code.
                if (!program.SegmentMap.IsValidAddress(addr))
                {
                    //$TODO: probably should use a reinterpret_cast here.
                    e = new Cast(ptr, c)
                    {
                        TypeVariable = c.TypeVariable
                    };
                    if (dereferenced)
                    {
                        e = new Dereference(ptr.Pointee, e);
                    }
                    return(e);
                }

                var dt       = ptr.Pointee.ResolveAs <DataType>();
                var charType = MaybeCharType(dt);
                if (charType != null && IsPtrToReadonlySection(c, dt))
                {
                    PromoteToCString(c, charType);
                    return(ReadNullTerminatedString(c, charType));
                }
                StructureField f          = EnsureFieldAtOffset(GlobalVars, dt, c.ToInt32());
                var            ptrGlobals = new Pointer(GlobalVars, platform.PointerType.BitSize);
                e = new FieldAccess(ptr.Pointee, new Dereference(ptrGlobals, globals), f);
                if (dereferenced)
                {
                    e.DataType = ptr.Pointee;
                }
                else
                {
                    if (f.DataType is ArrayType array) // C language rules 'promote' arrays to pointers.
                    {
                        e.DataType = program.TypeFactory.CreatePointer(
                            array.ElementType,
                            platform.PointerType.BitSize);
                    }
                    else
                    {
                        e = new UnaryExpression(Operator.AddrOf, ptr, e);
                    }
                }
            }
            return(e);
        }
Exemple #23
0
 public DataType VisitDereference(Dereference deref)
 {
     deref.Expression.Accept(this);
     return(handler.MemAccessTrait(null, deref.Expression, deref.Expression.DataType.Size, deref, 0));
 }
Exemple #24
0
 public override void VisitDereference(Dereference deref)
 {
     isCritical = true;
 }
Exemple #25
0
 public virtual void VisitDereference(Dereference deref)
 {
     deref.Expression.Accept(this);
 }
        private AssemblyOperation ParseAssemblyOperation()
        {
            var asterisk = NextToken(false);

            if (asterisk.IsOperator(Operator.Asterisk))
            {
                _stream.Next();
            }
            else
            {
                asterisk = null;
            }

            var reg = ParseRegister();

            var allowedOps = new HashSet <string>()
            {
                Operator.Assign,
                Operator.AssignPlus,
                Operator.AssignMinus,
                Operator.AssignShiftRight,
                Operator.AssignShiftLeft,
                Operator.AssignOr,
                Operator.AssignAnd,
                Operator.AssignXor,
                Operator.AssignLess,
                Operator.AssignGreater,
                Operator.AssignCond
            };
            var op = NextToken();

            if (op.Type != TokenType.Operator || !allowedOps.Contains(op.Value))
            {
                throw SyntaxError.Make(SyntaxErrorMessages.INVALID_TOKEN, op);
            }

            var node = new AssemblyOperation(op);

            if (asterisk != null)
            {
                var deref = new Dereference(asterisk);
                deref.AddChild(reg);

                node.AddChild(deref);
            }
            else
            {
                node.AddChild(reg);

                asterisk = NextToken(false);
                if (asterisk.IsOperator(Operator.Asterisk))
                {
                    _stream.Next();
                }
                else
                {
                    asterisk = null;
                }
            }

            // If we have two dereferences in the statement ParseRegister will fail
            reg = ParseRegister();

            if (asterisk != null)
            {
                var deref = new Dereference(asterisk);
                deref.AddChild(reg);

                node.AddChild(deref);
            }
            else
            {
                node.AddChild(reg);
            }

            if (!op.IsOperator(Operator.Assign) && asterisk != null)
            {
                throw SyntaxError.Make(SyntaxErrorMessages.INVALID_ASM_DEREFERENCE_USE(), node.Position);
            }

            return(node);
        }
Exemple #27
0
		public override void VisitDereference(Dereference deref)
		{
			isCritical = true;
		}
Exemple #28
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)
                    )
                );
        }
Exemple #29
0
 public bool VisitDereference(Dereference deref)
 {
     throw new NotImplementedException();
 }
		public override void VisitDereference(Dereference deref)
		{
			deref.Expression.Accept(this);
			EnsureTypeVariable(deref);
		}
Exemple #31
0
 public void VisitDereference(Dereference deref)
 {
     throw new NotImplementedException();
 }
Exemple #32
0
        public IErrorReporter ErrorHeapTypeAsValue()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    DiscardingAnyExpressionDuringTests = true,
                    AllowDereference = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                NameReference param_typename     = NameReference.Create("Hi");
                NameReference result_typename    = NameReference.Create("Hi");
                NameReference param_it_typename  = NameFactory.ItNameReference();
                NameReference result_it_typename = NameFactory.ItNameReference();

                Dereference bad_dereference = Dereference.Create(NameReference.CreateThised());

                NameReference decl_it_typename = NameFactory.ItNameReference();

                root_ns.AddBuilder(TypeBuilder.Create("Hi")
                                   .SetModifier(EntityModifier.HeapOnly)
                                   .Parents(NameFactory.IObjectNameReference())

                                   .With(FunctionBuilder.Create("named", result_typename,
                                                                Block.CreateStatement(
                                                                    VariableDeclaration.CreateStatement("n", null, bad_dereference),
                                                                    Return.Create(NameReference.Create("n"))))
                                         .Parameters(FunctionParameter.Create("p", param_typename, ExpressionReadMode.CannotBeRead)))

                                   .With(FunctionBuilder.Create("itted", result_it_typename,
                                                                Block.CreateStatement(
                                                                    VariableDeclaration.CreateStatement("it", decl_it_typename, Undef.Create()),
                                                                    Return.Create(NameReference.Create("it"))))
                                         .Parameters(FunctionParameter.Create("p", param_it_typename, ExpressionReadMode.CannotBeRead)))
                                   );

                var decl = VariableDeclaration.CreateStatement("bar", NameReference.Create("Hi"),
                                                               Undef.Create());

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "notimportant",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.UnitNameReference(),

                                       Block.CreateStatement(new[] {
                    decl,
                    ExpressionFactory.Readout("bar")
                })));

                resolver = NameResolver.Create(env);

                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.HeapTypeAsValue, decl.TypeName));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.HeapTypeAsValue, result_typename));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.HeapTypeAsValue, param_typename));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.HeapTypeAsValue, result_it_typename));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.HeapTypeAsValue, param_it_typename));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.HeapTypeAsValue, bad_dereference));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.HeapTypeAsValue, decl_it_typename));
                Assert.AreEqual(7, resolver.ErrorManager.Errors.Count);
            }

            return(resolver);
        }
Exemple #33
0
 public Expression VisitDereference(Dereference deref)
 {
     throw new NotImplementedException();
 }
Exemple #34
0
		public void VisitDereference(Dereference deref)
		{
			int prec = SetPrecedence(PrecedenceDereference);
			writer.Write("*");
			deref.Expression.Accept(this);
			ResetPresedence(prec);
		}
 public bool VisitDereference(Dereference deref, TypeVariable tv)
 {
     //$BUG: push (ptr (typeof(deref)
     deref.Expression.Accept(this, deref.Expression.TypeVariable);
     return(false);
 }
Exemple #36
0
 public DataType VisitDereference(Dereference deref)
 {
     throw new NotImplementedException();
 }