+2009-09-07 Marek Safar <marek.safar@gmail.com>
+
+ * *.cs: Changed Report class to accept various ouput printers and
+ be an instance class.
+
2009-09-04 Marek Safar <marek.safar@gmail.com>
* statement.cs, ecore.cs: Removed error reporting from emit code.
if (TypeManager.IsDelegateType (delegate_type))
return delegate_type;
- Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
+ ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
GetSignatureForError (), TypeManager.CSharpName (delegate_type));
return null;
}
- Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
+ ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
GetSignatureForError (), TypeManager.CSharpName (delegate_type));
return null;
}
- protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
+ protected bool VerifyExplicitParameters (ResolveContext ec, Type delegate_type, AParametersCollection parameters)
{
- if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
+ if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
return true;
- if (!ignore_error)
- Report.Error (1661, loc,
+ if (!ec.IsInProbingMode)
+ ec.Report.Error (1661, loc,
"Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
GetSignatureForError (), TypeManager.CSharpName (delegate_type));
return false;
}
- protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
+ protected bool VerifyParameterCompatibility (ResolveContext ec, Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
{
if (Parameters.Count != invoke_pd.Count) {
if (ignore_errors)
return false;
- Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
+ ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
return false;
}
return false;
if (p_mod == Parameter.Modifier.NONE)
- Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
+ ec.Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
(i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
else
- Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
+ ec.Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
(i+1).ToString (), Parameter.GetModifierSignature (p_mod));
error = true;
}
if (ignore_errors)
return false;
- Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
+ ec.Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
(i+1).ToString (),
TypeManager.CSharpName (Parameters.Types [i]),
TypeManager.CSharpName (invoke_pd.Types [i]));
//
// Infers type arguments based on explicit arguments
//
- public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
+ public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, Type delegate_type)
{
if (!HasExplicitParameters)
return false;
return false;
}
- AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
+ AParametersCollection d_params = TypeManager.GetDelegateParameters (ec, delegate_type);
if (d_params.Count != Parameters.Count)
return false;
// needed for the anonymous method. We create the method here.
//
- MethodInfo invoke_mb = Delegate.GetInvokeMethod (
+ MethodInfo invoke_mb = Delegate.GetInvokeMethod (ec.Compiler,
ec.CurrentType, delegate_type);
Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
//
try {
- int errors = Report.Errors;
+ int errors = ec.Report.Errors;
am = CompatibleMethod (ec, null, return_type, delegate_type);
- if (am != null && delegate_type != type && errors == Report.Errors)
+ if (am != null && delegate_type != type && errors == ec.Report.Errors)
am = CreateExpressionTree (ec, delegate_type);
if (!ec.IsInProbingMode)
public override Expression CreateExpressionTree (ResolveContext ec)
{
- Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
+ ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
return null;
}
protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, Type delegate_type)
{
- AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
+ AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (ec, delegate_type);
if (Parameters == ParametersCompiled.Undefined) {
//
for (int i = 0; i < delegate_parameters.Count; i++) {
Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
if (i_mod == Parameter.Modifier.OUT) {
- Report.Error (1688, loc, "Cannot convert anonymous " +
+ ec.Report.Error (1688, loc, "Cannot convert anonymous " +
"method block without a parameter list " +
"to delegate type `{0}' because it has " +
"one or more `out' parameters.",
return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
}
- if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
+ if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
return null;
}
public override Expression DoResolve (ResolveContext ec)
{
if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
- Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
+ ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
return null;
}
// nothing, as we only exist to not do anything.
}
- public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
+ public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
{
- Report.Error (1686, loc,
+ ec.Report.Error (1686, loc,
"Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
var.Name);
}
return_label = aec.ReturnLabel;
if (ec.HasSet (ResolveContext.Options.InferReturnType)) {
- aec.ReturnTypeInference.FixAllTypes ();
+ aec.ReturnTypeInference.FixAllTypes (ec);
ReturnType = aec.ReturnTypeInference.InferredTypeArguments [0];
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
- Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
+ ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
return null;
}
ig.Emit (OpCodes.Ldftn, delegate_method);
- ConstructorInfo constructor_method = Delegate.GetConstructor (ec.CurrentType, type);
+ ConstructorInfo constructor_method = Delegate.GetConstructor (RootContext.ToplevelTypes.Compiler, ec.CurrentType, type);
#if MS_COMPATIBLE
if (type.IsGenericType && type is TypeBuilder)
constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
{
}
- protected override void ErrorDuplicateName (Parameter p)
+ protected override void ErrorDuplicateName (Parameter p, Report Report)
{
Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
p.Name);
this.parameters = parameters;
}
- public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
+ public static AnonymousTypeClass Create (CompilerContext ctx, TypeContainer parent, ArrayList parameters, Location loc)
{
string name = ClassNamePrefix + types_counter++;
Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
null, new AnonymousParameters (ctor_params), null, loc);
- c.Block = new ToplevelBlock (c.Parameters, loc);
+ c.Block = new ToplevelBlock (ctx, c.Parameters, loc);
//
// Create fields and contructor body with field initialization
new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
c.Block.GetParameterReference (p.Name, p.Location))));
- ToplevelBlock get_block = new ToplevelBlock (p.Location);
+ ToplevelBlock get_block = new ToplevelBlock (ctx, p.Location);
get_block.AddStatement (new Return (
new MemberAccess (new This (p.Location), f.Name), p.Location));
Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
- ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
+ ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.Parameters, loc);
TypeExpr current_type;
if (IsGeneric)
current_type = new GenericTypeExpr (this, loc);
// hash ^= hash >> 17;
// hash += hash << 5;
- ToplevelBlock hashcode_top = new ToplevelBlock (loc);
+ ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
Block hashcode_block = new Block (hashcode_top);
hashcode_top.AddStatement (new Unchecked (hashcode_block));
// ToString () override
//
- ToplevelBlock tostring_block = new ToplevelBlock (loc);
+ ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
tostring_block.AddStatement (new Return (string_concat, loc));
tostring.Block = tostring_block;
tostring.Define ();
public virtual Expression CreateExpressionTree (ResolveContext ec)
{
if (ArgType == AType.Default)
- Report.Error (854, Expr.Location, "An expression tree cannot contain an invocation which uses optional parameter");
+ ec.Report.Error (854, Expr.Location, "An expression tree cannot contain an invocation which uses optional parameter");
return Expr.CreateExpressionTree (ec);
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
- Report.Error (853, Name.Location, "An expression tree cannot contain named argument");
+ ec.Report.Error (853, Name.Location, "An expression tree cannot contain named argument");
return base.CreateExpressionTree (ec);
}
return all;
}
- public void CheckArrayAsAttribute ()
+ public void CheckArrayAsAttribute (CompilerContext ctx)
{
foreach (Argument arg in args) {
// Type is undefined (was error 246)
continue;
if (arg.Type.IsArray)
- Report.Warning (3016, 1, arg.Expr.Location, "Arrays as attribute arguments are not CLS-compliant");
+ ctx.Report.Warning (3016, 1, arg.Expr.Location, "Arrays as attribute arguments are not CLS-compliant");
}
}
{
Arguments args = new Arguments (1);
args.Add (new Argument (this));
- return CreateExpressionFactoryCall ("Constant", args);
+ return CreateExpressionFactoryCall (ec, "Constant", args);
}
public override Expression DoResolve (ResolveContext ec)
public override Expression CreateExpressionTree (ResolveContext ec)
{
- Report.Error (832, loc, "An expression tree cannot contain an assignment operator");
+ ec.Report.Error (832, loc, "An expression tree cannot contain an assignment operator");
return null;
}
type = target_type;
if (!(target is IAssignMethod)) {
- Error_ValueAssignment (loc);
+ Error_ValueAssignment (ec, loc);
return null;
}
if ((RootContext.Version == LanguageVersion.ISO_1) &&
(source is MethodGroupExpr)){
- ((MethodGroupExpr) source).ReportUsageError ();
+ ((MethodGroupExpr) source).ReportUsageError (ec);
return null;
}
return e;
if (CheckEqualAssign (target))
- Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
+ ec.Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
return this;
}
public override Expression DoResolve (ResolveContext ec)
{
if (op != Binary.Operator.Addition && op != Binary.Operator.Subtraction)
- target.Error_AssignmentEventOnly ();
+ target.Error_AssignmentEventOnly (ec);
source = source.Resolve (ec);
if (source == null)
return null;
if (target is MethodGroupExpr){
- Error_CannotAssign (((MethodGroupExpr)target).Name, target.ExprClassName);
+ ec.Report.Error (1656, loc,
+ "Cannot assign to `{0}' because it is a `{1}'",
+ ((MethodGroupExpr)target).Name, target.ExprClassName);
return null;
}
target.OptAttributes = null;
}
- void Error_InvalidNamedArgument (NamedArgument name)
+ static void Error_InvalidNamedArgument (ResolveContext rc, NamedArgument name)
{
- Report.Error (617, name.Name.Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
+ rc.Report.Error (617, name.Name.Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
"must be fields which are not readonly, static, const or read-write properties which are " +
"public and not static",
name.Name.Value);
}
- void Error_InvalidNamedArgumentType (NamedArgument name)
+ static void Error_InvalidNamedArgumentType (ResolveContext rc, NamedArgument name)
{
- Report.Error (655, name.Name.Location,
+ rc.Report.Error (655, name.Name.Location,
"`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type",
name.Name.Value);
}
- public static void Error_AttributeArgumentNotValid (Location loc)
+ public static void Error_AttributeArgumentNotValid (ResolveContext rc, Location loc)
{
- Report.Error (182, loc,
+ rc.Report.Error (182, loc,
"An attribute argument must be a constant expression, typeof " +
"expression or array creation expression");
}
/// </summary>
void ResolveAttributeType ()
{
- Report.IMessageRecorder msg_recorder = new Report.MessageRecorder ();
- Report.IMessageRecorder prev_recorder = Report.SetMessageRecorder (msg_recorder);
- int errors = Report.Errors;
+ SessionReportPrinter resolve_printer = new SessionReportPrinter ();
+ ReportPrinter prev_recorder = context.Compiler.Report.SetPrinter (resolve_printer);
bool t1_is_attr = false;
- Type t1 = ResolvePossibleAttributeType (expression, ref t1_is_attr);
-
bool t2_is_attr = false;
- Type t2;
+ Type t1, t2;
ATypeNameExpression expanded = null;
- if (nameEscaped) {
- t2 = null;
- } else {
- expanded = (ATypeNameExpression) expression.Clone (null);
- expanded.Name += "Attribute";
+ try {
+ t1 = ResolvePossibleAttributeType (expression, ref t1_is_attr);
- t2 = ResolvePossibleAttributeType (expanded, ref t2_is_attr);
- }
+ if (nameEscaped) {
+ t2 = null;
+ } else {
+ expanded = (ATypeNameExpression) expression.Clone (null);
+ expanded.Name += "Attribute";
- msg_recorder.EndSession ();
- Report.SetMessageRecorder (prev_recorder);
- Report.Errors = errors;
+ t2 = ResolvePossibleAttributeType (expanded, ref t2_is_attr);
+ }
+
+ resolve_printer.EndSession ();
+ } finally {
+ context.Compiler.Report.SetPrinter (prev_recorder);
+ }
if (t1_is_attr && t2_is_attr) {
Report.Error (1614, Location, "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}Attribute'",
return;
}
- msg_recorder.PrintMessages ();
+ resolve_printer.Merge (prev_recorder);
resolve_error = true;
}
Constant.CreateConstant (typeof (CharSet), RootContext.ToplevelTypes.DefaultCharSet, Location)));
}
+ Report Report {
+ get { return context.Compiler.Report; }
+ }
+
public CustomAttributeBuilder Resolve ()
{
if (resolve_error)
ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
if (obsolete_attr != null) {
- AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
+ AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location, Report);
}
if (PosArguments == null && NamedArguments == null) {
return cb;
}
catch (Exception) {
- Error_AttributeArgumentNotValid (Location);
+ Error_AttributeArgumentNotValid (rc, Location);
return null;
}
}
}
if (Type == pa.AttributeUsage && (int)pos_values [0] == 0) {
- Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
+ ec.Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
return null;
}
if (Type == pa.IndexerName || Type == pa.Conditional) {
string v = pos_values [0] as string;
if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
- Report.Error (633, PosArguments [0].Expr.Location,
+ ec.Report.Error (633, PosArguments [0].Expr.Location,
"The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
return null;
}
foreach (NamedArgument a in NamedArguments) {
string name = a.Name.Value;
if (seen_names.Contains (name)) {
- Report.Error (643, a.Name.Location, "Duplicate named attribute `{0}' argument", name);
+ ec.Report.Error (643, a.Name.Location, "Duplicate named attribute `{0}' argument", name);
continue;
}
a.Resolve (ec);
- Expression member = Expression.MemberLookup (
+ Expression member = Expression.MemberLookup (ec.Compiler,
ec.CurrentType, Type, name,
MemberTypes.All,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static,
Location);
if (member == null) {
- member = Expression.MemberLookup (ec.CurrentType, Type, name,
+ member = Expression.MemberLookup (ec.Compiler, ec.CurrentType, Type, name,
MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
Location);
if (member != null) {
- Report.SymbolRelatedToPreviousError (member.Type);
- Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
+ ec.Report.SymbolRelatedToPreviousError (member.Type);
+ Expression.ErrorIsInaccesible (Location, member.GetSignatureForError (), ec.Report);
return false;
}
}
if (member == null){
- Expression.Error_TypeDoesNotContainDefinition (Location, Type, name);
+ Expression.Error_TypeDoesNotContainDefinition (ec, Location, Type, name);
return false;
}
if (!(member is PropertyExpr || member is FieldExpr)) {
- Error_InvalidNamedArgument (a);
+ Error_InvalidNamedArgument (ec, a);
return false;
}
PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
if (!pi.CanWrite || !pi.CanRead || pi.GetGetMethod ().IsStatic) {
- Report.SymbolRelatedToPreviousError (pi);
- Error_InvalidNamedArgument (a);
+ ec.Report.SymbolRelatedToPreviousError (pi);
+ Error_InvalidNamedArgument (ec, a);
return false;
}
if (!IsValidArgumentType (member.Type)) {
- Report.SymbolRelatedToPreviousError (pi);
- Error_InvalidNamedArgumentType (a);
+ ec.Report.SymbolRelatedToPreviousError (pi);
+ Error_InvalidNamedArgumentType (ec, a);
return false;
}
FieldInfo fi = ((FieldExpr) member).FieldInfo;
if (fi.IsInitOnly || fi.IsStatic) {
- Error_InvalidNamedArgument (a);
+ Error_InvalidNamedArgument (ec, a);
return false;
}
if (!IsValidArgumentType (member.Type)) {
- Report.SymbolRelatedToPreviousError (fi);
- Error_InvalidNamedArgumentType (a);
+ ec.Report.SymbolRelatedToPreviousError (fi);
+ Error_InvalidNamedArgumentType (ec, a);
return false;
}
}
if (obsolete_attr != null && !context.IsObsolete)
- AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location);
+ AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location, Report);
}
prop_info_arr = new PropertyInfo [prop_infos.Count];
// Here we are testing attribute arguments for array usage (error 3016)
if (Owner.IsClsComplianceRequired ()) {
if (PosArguments != null)
- PosArguments.CheckArrayAsAttribute ();
+ PosArguments.CheckArrayAsAttribute (context.Compiler);
if (NamedArguments == null)
return;
- NamedArguments.CheckArrayAsAttribute ();
+ NamedArguments.CheckArrayAsAttribute (context.Compiler);
}
}
if (d.Value == null)
continue;
+ Report report = RootContext.ToplevelTypes.Compiler.Report;
foreach (Attribute collision in (ArrayList)d.Value)
- Report.SymbolRelatedToPreviousError (collision.Location, "");
+ report.SymbolRelatedToPreviousError (collision.Location, "");
Attribute a = (Attribute)d.Key;
- Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
+ report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
a.GetSignatureForError ());
}
}
return (IFixedBuffer)o;
}
- public static void VerifyModulesClsCompliance ()
+ public static void VerifyModulesClsCompliance (CompilerContext ctx)
{
Module[] modules = GlobalRootNamespace.Instance.Modules;
if (modules == null)
for (int i = 1; i < modules.Length; ++i) {
Module module = modules [i];
if (!GetClsCompliantAttributeValue (module, null)) {
- Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
+ ctx.Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
"to match the assembly", module.Name);
return;
}
/// <summary>
/// Common method for Obsolete error/warning reporting.
/// </summary>
- public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
+ public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
{
if (oa.IsError) {
Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
return false;
}
- type = TypeManager.CoreLookupType (ns, name, Kind.Class, !canFail);
+ type = TypeManager.CoreLookupType (RootContext.ToplevelTypes.Compiler, ns, name, Kind.Class, !canFail);
if (type == null) {
type = typeof (PredefinedAttribute);
return false;
return false;
}
- internal static void Error_CompileTimeOverflow (Location loc)
+ internal static void Error_CompileTimeOverflow (ResolveContext rc, Location loc)
{
- Report.Error (220, loc, "The operation overflows at compile time in checked mode");
+ rc.Report.Error (220, loc, "The operation overflows at compile time in checked mode");
}
/// <summary>
result = new DecimalConstant (res, left.Location);
}
} catch (OverflowException){
- Error_CompileTimeOverflow (loc);
+ Error_CompileTimeOverflow (ec, loc);
}
return result;
throw new Exception ( "Unexepected subtraction input: " + left);
}
} catch (OverflowException){
- Error_CompileTimeOverflow (loc);
+ Error_CompileTimeOverflow (ec, loc);
}
return result;
throw new Exception ( "Unexepected multiply input: " + left);
}
} catch (OverflowException){
- Error_CompileTimeOverflow (loc);
+ Error_CompileTimeOverflow (ec, loc);
}
break;
throw new Exception ( "Unexepected division input: " + left);
}
} catch (OverflowException){
- Error_CompileTimeOverflow (loc);
+ Error_CompileTimeOverflow (ec, loc);
} catch (DivideByZeroException) {
- Report.Error (020, loc, "Division by constant zero");
+ ec.Report.Error (20, loc, "Division by constant zero");
}
break;
throw new Exception ( "Unexepected modulus input: " + left);
}
} catch (DivideByZeroException){
- Report.Error (020, loc, "Division by constant zero");
+ ec.Report.Error (20, loc, "Division by constant zero");
} catch (OverflowException){
- Error_CompileTimeOverflow (loc);
+ Error_CompileTimeOverflow (ec, loc);
}
break;
case Binary.Operator.LeftShift:
IntConstant ic = right.ConvertImplicitly (TypeManager.int32_type) as IntConstant;
if (ic == null){
- Binary.Error_OperatorCannotBeApplied (left, right, oper, loc);
+ Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc);
return null;
}
if (left.Type == TypeManager.int32_type)
return new IntConstant (((IntConstant)left).Value << lshift_val, left.Location);
- Binary.Error_OperatorCannotBeApplied (left, right, oper, loc);
+ Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc);
break;
//
case Binary.Operator.RightShift:
IntConstant sic = right.ConvertImplicitly (TypeManager.int32_type) as IntConstant;
if (sic == null){
- Binary.Error_OperatorCannotBeApplied (left, right, oper, loc); ;
+ Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc); ;
return null;
}
int rshift_val = sic.Value;
if (left.Type == TypeManager.int32_type)
return new IntConstant (((IntConstant)left).Value >> rshift_val, left.Location);
- Binary.Error_OperatorCannotBeApplied (left, right, oper, loc);
+ Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc);
break;
case Binary.Operator.Equality:
continue;
Operator o = operators [i];
- Report.Error (216, o.Location,
+ container.Report.Error (216, o.Location,
"The operator `{0}' requires a matching operator `{1}' to also be defined",
o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
}
- if (has_equality_or_inequality && Report.WarningLevel > 2) {
+ if (has_equality_or_inequality && container.Report.WarningLevel > 2) {
if (container.Methods == null || !container.HasEquals)
- Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
+ container.Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
if (container.Methods == null || !container.HasGetHashCode)
- Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
+ container.Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
}
}
#region IMemberContext Members
+ public CompilerContext Compiler {
+ get { return tc.Compiler; }
+ }
+
public Type CurrentType {
get { return tc.Parent.CurrentType; }
}
int type_size = Kind == Kind.Struct && first_nonstatic_field == null ? 1 : 0;
if (IsTopLevel){
- if (TypeManager.NamespaceClash (Name, Location)) {
+ if (GlobalRootNamespace.Instance.IsNamespace (Name)) {
+ Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
return false;
}
ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
if ((oa != null) && !IsObsolete)
AttributeTester.Report_ObsoleteMessage (
- oa, iface.GetSignatureForError (), Location);
+ oa, iface.GetSignatureForError (), Location, Report);
GenericTypeExpr ct = iface as GenericTypeExpr;
if (ct != null) {
if (base_type != null) {
ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
if (obsolete_attr != null && !IsObsolete)
- AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
+ AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
GenericTypeExpr ct = base_type as GenericTypeExpr;
if ((ct != null) && !ct.CheckConstraints (this))
return;
}
- static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
+ void CheckMemberUsage (MemberCoreArrayList al, string member_type)
{
if (al == null)
return;
}
if (pending != null)
- pending.VerifyPendingMethods ();
+ pending.VerifyPendingMethods (Report);
if (Report.Errors > 0)
return;
if (Kind == Kind.Struct){
if ((flags & va) != 0){
- Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
+ Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract", Report);
ok = false;
}
}
//
internal override void GenerateDocComment (DeclSpace ds)
{
- DocUtil.GenerateTypeDocComment (this, ds);
+ DocUtil.GenerateTypeDocComment (this, ds, Report);
}
public override string DocCommentHeader {
Location);
AddConstructor (c);
- c.Block = new ToplevelBlock (ParametersCompiled.EmptyReadOnlyParameters, Location);
+ c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
}
public override bool Define ()
: base (ns, parent, name, attrs, Kind.Class)
{
int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
- this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
+ this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location, Report);
if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
Report.FeatureIsNotAvailable (Location, "static classes");
else
accmods = Modifiers.PRIVATE;
- this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
+ this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location, Report);
this.ModFlags |= Modifiers.SEALED;
}
else
accmods = Modifiers.PRIVATE;
- this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
+ this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location, Report);
}
public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
//
internal override void OnGenerateDocComment (XmlElement el)
{
- DocUtil.OnMethodGenerateDocComment (this, el);
+ DocUtil.OnMethodGenerateDocComment (this, el, Report);
}
//
protected virtual bool CheckForDuplications ()
{
return Parent.MemberCache.CheckExistingMembersOverloads (
- this, GetFullName (MemberName), ParametersCompiled.EmptyReadOnlyParameters);
+ this, GetFullName (MemberName), ParametersCompiled.EmptyReadOnlyParameters, Report);
}
//
Parent.PartialContainer.VerifyImplements (this);
}
- Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
+ Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
}
return base.Define ();
Parameter p = parameters [i];
if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
- p.Warning_UselessOptionalParameter ();
+ p.Warning_UselessOptionalParameter (Report);
if (p.CheckAccessibility (this))
continue;
if (MemberName.IsGeneric)
name = MemberName.MakeName (name, MemberName.TypeArguments);
- return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters);
+ return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters, Report);
}
public virtual EmitContext CreateEmitContext (ILGenerator ig)
// Current method is turned into automatically generated
// wrapper which creates an instance of iterator
//
- Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+ Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
ModFlags |= Modifiers.DEBUGGER_HIDDEN;
}
MethodData = new MethodData (
this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
- if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
+ if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName), Report))
return false;
MethodBuilder = MethodData.MethodBuilder;
}
if (p.HasDefaultValue && IsPartialImplementation)
- ((Parameter) p).Warning_UselessOptionalParameter ();
+ ((Parameter) p).Warning_UselessOptionalParameter (Report);
}
}
}
return base.GetSignatureForError () + Parameters.GetSignatureForError ();
}
- static void Error_DuplicateEntryPoint (Method b)
+ void Error_DuplicateEntryPoint (Method b)
{
Report.Error (17, b.Location,
"Program `{0}' has more than one entry point defined: `{1}'",
MethodBuilder = partialMethodImplementation.MethodBuilder;
if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
- Error1599 (Location, ReturnType);
+ Error1599 (Location, ReturnType, Report);
return false;
}
return base.EnableOverloadChecks (overload);
}
- public static void Error1599 (Location loc, Type t)
+ public static void Error1599 (Location loc, Type t, Report Report)
{
Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
}
if (!Parameters.IsEmpty) {
ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
if (al.Count > 1)
- MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
+ MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder, Report);
}
return true;
type = ec.CurrentType.BaseType;
if (TypeManager.IsStruct (ec.CurrentType)) {
- Report.Error (522, loc,
+ ec.Report.Error (522, loc,
"`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
return this;
}
ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
if (base_ctor == caller_builder){
- Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
+ ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
}
return this;
if ((caching_flags & Flags.MethodOverloadsExist) != 0)
Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
- Parameters);
+ Parameters, Report);
if (Parent.PartialContainer.Kind == Kind.Struct) {
if (Parameters.Count == 0) {
// It's here only to report an error
if (block != null && block.IsIterator) {
member_type = TypeManager.void_type;
- Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+ Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
}
return true;
if (!Parameters.IsEmpty) {
ArrayList al = (ArrayList)Parent.MemberCache.Members [ConstructorInfo.ConstructorName];
if (al.Count > 2)
- MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
+ MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder, Report);
if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
foreach (Type param in Parameters.Types) {
this.parent_method = parent_method;
}
- public bool Define (DeclSpace parent, string method_full_name)
+ public bool Define (DeclSpace parent, string method_full_name, Report Report)
{
string name = method.MethodName.Basename;
methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
methodbuilder_attrs_field.SetValue (builder, flags);
} catch {
- Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
+ RootContext.ToplevelTypes.Compiler.Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
}
}
}
Type base_type = Parent.PartialContainer.BaseCache.Container.Type;
if (base_type != null && Block != null) {
- MethodGroupExpr method_expr = Expression.MethodLookup (Parent.TypeBuilder, base_type, MetadataName, Location);
+ MethodGroupExpr method_expr = Expression.MethodLookup (Parent.Module.Compiler, Parent.TypeBuilder, base_type, MetadataName, Location);
if (method_expr == null)
throw new NotImplementedException ();
method_expr.IsBase = true;
method_expr.InstanceExpression = new CompilerGeneratedThis (Parent.TypeBuilder, Location);
- ToplevelBlock new_block = new ToplevelBlock (Block.StartLocation);
+ ToplevelBlock new_block = new ToplevelBlock (Compiler, Block.StartLocation);
new_block.EndLocation = Block.EndLocation;
Block finaly_block = new ExplicitBlock (new_block, Location, Location);
{
this.ds = generic != null ? generic : (DeclSpace) parent;
this.type_name = type;
- ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
+ ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location, Report);
GenericMethod = generic;
if (GenericMethod != null)
GenericMethod.ModFlags = ModFlags;
return;
if (MemberType.IsSealed && MemberType.IsAbstract) {
- Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
+ Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
}
CheckBase ();
base.Emit ();
}
- public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
+ public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class, Report Report)
{
Report.SymbolRelatedToPreviousError (static_class);
Report.Error (723, loc, "`{0}': cannot declare variables of static types",
base.DoMemberTypeIndependentChecks ();
if (!Parent.IsUnsafe)
- Expression.UnsafeError (Location);
+ Expression.UnsafeError (Report, Location);
if (Parent.PartialContainer.Kind != Kind.Struct) {
Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
Type[] required_modifier = null;
if ((ModFlags & Modifiers.VOLATILE) != 0) {
if (TypeManager.isvolatile_type == null)
- TypeManager.isvolatile_type = TypeManager.CoreLookupType (
+ TypeManager.isvolatile_type = TypeManager.CoreLookupType (Compiler,
"System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
if (TypeManager.isvolatile_type != null)
Attributes = attrs;
Location = loc;
Parameters = p;
- ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
+ ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc, RootContext.ToplevelTypes.Compiler.Report);
}
}
method_data = new MethodData (method, ModFlags, flags, this);
- if (!method_data.Define (parent, method.GetFullName (MemberName)))
+ if (!method_data.Define (parent, method.GetFullName (MemberName), Report))
return null;
return method_data.MethodBuilder;
method_data = new MethodData (method, ModFlags, flags, this);
- if (!method_data.Define (parent, method.GetFullName (MemberName)))
+ if (!method_data.Define (parent, method.GetFullName (MemberName), Report))
return null;
return method_data.MethodBuilder;
CheckAbstractAndExtern (block != null);
if (block != null && block.IsIterator)
- Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+ Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
return null;
}
if ((caching_flags & Flags.MethodOverloadsExist) == 0)
return true;
- return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
+ return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo, Report);
}
}
fe.InstanceExpression = new CompilerGeneratedThis (fe.Type, Location);
// Create get block
- Get.Block = new ToplevelBlock (ParametersCompiled.EmptyReadOnlyParameters, Location);
+ Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
Return r = new Return (fe, Location);
Get.Block.AddStatement (r);
// Create set block
- Set.Block = new ToplevelBlock (Set.ParameterInfo, Location);
+ Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location);
Assign a = new SimpleAssign (fe, new SimpleName ("value", Location));
Set.Block.AddStatement (new StatementExpression (a));
}
if ((method.ModFlags & Modifiers.STATIC) == 0)
f_expr.InstanceExpression = new CompilerGeneratedThis (field_info.FieldType, Location);
- block = new ToplevelBlock (ParameterInfo, Location);
+ block = new ToplevelBlock (Compiler, ParameterInfo, Location);
block.AddStatement (new StatementExpression (
new CompoundAssign (Operation,
f_expr,
method_data = new MethodData (method, method.ModFlags,
method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
- if (!method_data.Define (parent, method.GetFullName (MemberName)))
+ if (!method_data.Define (parent, method.GetFullName (MemberName), Report))
return null;
MethodBuilder mb = method_data.MethodBuilder;
protected override bool CheckForDuplications ()
{
- return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters);
+ return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters, Report);
}
public override bool Define ()
// imlicit and explicit operator of same types are not allowed
if (OperatorType == OpType.Explicit)
- Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
+ Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters, Report);
else if (OperatorType == OpType.Implicit)
- Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
+ Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters, Report);
Type declaring_type = MethodData.DeclaringType;
Type return_type = MemberType;
//
// Initializes the code generator variables for interactive use (repl)
//
- static public void InitDynamic (string name)
+ static public void InitDynamic (CompilerContext ctx, string name)
{
current_domain = AppDomain.CurrentDomain;
AssemblyName an = Assembly.GetAssemblyName (name, name);
Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run | COMPILER_ACCESS);
- RootContext.ToplevelTypes = new ModuleContainer (true);
+ RootContext.ToplevelTypes = new ModuleContainer (ctx, true);
RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false);
Assembly.Name = Assembly.Builder.GetName ();
}
//
// Initializes the code generator variables
//
- static public bool Init (string name, string output, bool want_debugging_support)
+ static public bool Init (string name, string output, bool want_debugging_support, CompilerContext ctx)
{
FileName = output;
AssemblyName an = Assembly.GetAssemblyName (name, output);
AssemblyName ref_name = a.GetName ();
byte [] b = ref_name.GetPublicKeyToken ();
if (b == null || b.Length == 0) {
- Report.Error (1577, "Assembly generation failed " +
+ ctx.Report.Error (1577, "Assembly generation failed " +
"-- Referenced assembly '" +
ref_name.Name +
"' does not have a strong name.");
catch (ArgumentException) {
// specified key may not be exportable outside it's container
if (RootContext.StrongNameKeyContainer != null) {
- Report.Error (1548, "Could not access the key inside the container `" +
+ ctx.Report.Error (1548, "Could not access the key inside the container `" +
RootContext.StrongNameKeyContainer + "'.");
Environment.Exit (1);
}
}
catch (CryptographicException) {
if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
- Report.Error (1548, "Could not use the specified key to strongname the assembly.");
+ ctx.Report.Error (1548, "Could not use the specified key to strongname the assembly.");
Environment.Exit (1);
}
return false;
#if !MS_COMPATIBLE
// TODO: We should use SymbolWriter from DefineDynamicModule
if (want_debugging_support && !SymbolWriter.Initialize (RootContext.ToplevelTypes.Builder, output)) {
- Report.Error (40, "Unexpected debug information initialization error `{0}'",
+ ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'",
"Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
return false;
}
#endif
} catch (ExecutionEngineException e) {
- Report.Error (40, "Unexpected debug information initialization error `{0}'",
+ ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'",
e.Message);
return false;
}
return true;
}
- static public void Save (string name, bool saveDebugInfo)
+ static public void Save (string name, bool saveDebugInfo, Report Report)
{
#if GMCS_SOURCE
PortableExecutableKinds pekind;
#region IMemberContext Members
+ public CompilerContext Compiler {
+ get { return RootContext.ToplevelTypes.Compiler; }
+ }
+
public Type CurrentType {
get { return null; }
}
// Module is here just because of error messages
static string[] attribute_targets = new string [] { "assembly", "module" };
- public AssemblyClass (): base ()
+ public AssemblyClass ()
{
wrap_non_exception_throws = true;
}
return is_cls_compliant;
}
+ Report Report {
+ get { return Compiler.Report; }
+ }
+
public void Resolve ()
{
if (RootContext.Unsafe) {
Type expr_type = expr_resolved.Type;
if (expr_type.IsPointer || expr_type == TypeManager.void_type || expr_type == TypeManager.null_type || expr_type == InternalType.AnonymousMethod) {
- Unary.Error_OperatorCannotBeApplied (loc, ".", expr_type);
+ Unary.Error_OperatorCannotBeApplied (ec, loc, ".", expr_type);
return null;
}
Type ttype = MemberType;
if (!IsConstantTypeValid (ttype)) {
- Error_InvalidConstantType (ttype, Location);
+ Error_InvalidConstantType (ttype, Location, Report);
}
// If the constant is private then we don't need any field the
return new CustomAttributeBuilder (pa.Constructor, args);
}
- public static void Error_ExpressionMustBeConstant (Location loc, string e_name)
+ public static void Error_ExpressionMustBeConstant (Location loc, string e_name, Report Report)
{
Report.Error (133, loc, "The expression being assigned to `{0}' must be constant", e_name);
}
- public static void Error_CyclicDeclaration (MemberCore mc)
+ public static void Error_CyclicDeclaration (MemberCore mc, Report Report)
{
Report.Error (110, mc.Location, "The evaluation of the constant value for `{0}' involves a circular definition",
mc.GetSignatureForError ());
}
- public static void Error_ConstantCanBeInitializedWithNullOnly (Type type, Location loc, string name)
+ public static void Error_ConstantCanBeInitializedWithNullOnly (Type type, Location loc, string name, Report Report)
{
Report.Error (134, loc, "A constant `{0}' of reference type `{1}' can only be initialized with null",
name, TypeManager.CSharpName (type));
}
- public static void Error_InvalidConstantType (Type t, Location loc)
+ public static void Error_InvalidConstantType (Type t, Location loc, Report Report)
{
if (TypeManager.IsGenericParameter (t)) {
Report.Error (1959, loc,
SetMemberIsUsed ();
if (in_transit) {
- Error_CyclicDeclaration (this);
+ Error_CyclicDeclaration (this, Report);
// Suppress cyclic errors
value = New.Constantify (MemberType);
resolved = true;
Constant c = value.ConvertImplicitly (MemberType);
if (c == null) {
if (TypeManager.IsReferenceType (MemberType))
- Error_ConstantCanBeInitializedWithNullOnly (MemberType, Location, GetSignatureForError ());
+ Error_ConstantCanBeInitializedWithNullOnly (MemberType, Location, GetSignatureForError (), Report);
else
value.Error_ValueCannotBeConverted (ec, Location, MemberType, false);
}
return;
}
- AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), loc);
+ AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), loc, RootContext.ToplevelTypes.Compiler.Report);
}
public bool ResolveValue ()
if (!expl && IsLiteral &&
(TypeManager.IsPrimitiveType (target) || type == TypeManager.decimal_type) &&
(TypeManager.IsPrimitiveType (type) || type == TypeManager.decimal_type)) {
- Report.Error (31, loc, "Constant value `{0}' cannot be converted to a `{1}'",
+ ec.Report.Error (31, loc, "Constant value `{0}' cannot be converted to a `{1}'",
AsString (), TypeManager.CSharpName (target));
} else {
base.Error_ValueCannotBeConverted (ec, loc, target, expl);
args.Add (new Argument (this));
args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
- return CreateExpressionFactoryCall ("Constant", args);
+ return CreateExpressionFactoryCall (ec, "Constant", args);
}
}
catch (OverflowException) {
if (ec.ConstantCheckState) {
- Report.Error (221, loc, "Constant value `{0}' cannot be converted to a `{1}' (use `unchecked' syntax to override)",
+ ec.Report.Error (221, loc, "Constant value `{0}' cannot be converted to a `{1}' (use `unchecked' syntax to override)",
GetValue ().ToString (), TypeManager.CSharpName (target_type));
} else {
Error_ValueCannotBeConverted (ec, loc, target_type, false);
}
catch
{
- Report.Error (31, loc, "Constant value `{0}' cannot be converted to a `{1}'",
+ ec.Report.Error (31, loc, "Constant value `{0}' cannot be converted to a `{1}'",
GetValue ().ToString (), TypeManager.CSharpName (target));
}
}
ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc);
FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104);
FullNamedExpression LookupNamespaceAlias (string name);
+
+ CompilerContext Compiler { get; }
}
//
oldval = ec.flags & mask;
ec.flags = (ec.flags & invmask) | (val & mask);
- if ((mask & Options.ProbingMode) != 0)
- Report.DisableReporting ();
+// if ((mask & Options.ProbingMode) != 0)
+// ec.Report.DisableReporting ();
}
public void Dispose ()
{
- if ((invmask & Options.ProbingMode) == 0)
- Report.EnableReporting ();
+// if ((invmask & Options.ProbingMode) == 0)
+// ec.Report.EnableReporting ();
ec.flags = (ec.flags & invmask) | oldval;
}
flags |= options;
}
+ public CompilerContext Compiler {
+ get { return MemberContext.Compiler; }
+ }
+
public virtual FlowBranching CurrentBranching {
get { return null; }
}
return (this.flags & options) != 0;
}
+ public Report Report {
+ get {
+ return Compiler.Report;
+ }
+ }
+
// Temporarily set all the given flags to the given value. Should be used in an 'using' statement
public FlagsHandle Set (Options options)
{
return result;
}
}
+
+ //
+ // Main compiler context
+ //
+ public class CompilerContext
+ {
+ readonly Report report;
+
+ public CompilerContext (Report report)
+ {
+ this.report = report;
+ }
+
+ public Report Report {
+ get { return report; }
+ }
+
+ //public PredefinedAttributes PredefinedAttributes {
+ // get { throw new NotImplementedException (); }
+ //}
+ }
}
\ No newline at end of file
if (TypeManager.IsEqual (expr_type, target_type))
return true;
- if (TypeManager.IsNullableType (target_type))
+ if (TypeManager.IsNullableType (target_type)) {
return ImplicitNulableConversion (null, expr, target_type) != null;
+ }
// First numeric conversions
if (ImplicitNumericConversion (null, expr_type, target_type) != null)
/// Compute the user-defined conversion operator from source_type to target_type.
/// `look_for_explicit' controls whether we should also include the list of explicit operators
/// </summary>
- static MethodInfo GetConversionOperator (Type container_type, Expression source, Type target_type, bool look_for_explicit)
+ static MethodInfo GetConversionOperator (CompilerContext ctx, Type container_type, Expression source, Type target_type, bool look_for_explicit)
{
ArrayList ops = new ArrayList (4);
if (source_type != TypeManager.decimal_type) {
AddConversionOperators (ops, source, target_type, look_for_explicit,
- Expression.MethodLookup (container_type, source_type, "op_Implicit", Location.Null) as MethodGroupExpr);
+ Expression.MethodLookup (ctx, container_type, source_type, "op_Implicit", Location.Null) as MethodGroupExpr);
if (look_for_explicit) {
AddConversionOperators (ops, source, target_type, look_for_explicit,
- Expression.MethodLookup (
+ Expression.MethodLookup (ctx,
container_type, source_type, "op_Explicit", Location.Null) as MethodGroupExpr);
}
}
if (target_type != TypeManager.decimal_type) {
AddConversionOperators (ops, source, target_type, look_for_explicit,
- Expression.MethodLookup (container_type, target_type, "op_Implicit", Location.Null) as MethodGroupExpr);
+ Expression.MethodLookup (ctx, container_type, target_type, "op_Implicit", Location.Null) as MethodGroupExpr);
if (look_for_explicit) {
AddConversionOperators (ops, source, target_type, look_for_explicit,
- Expression.MethodLookup (
+ Expression.MethodLookup (ctx,
container_type, target_type, "op_Explicit", Location.Null) as MethodGroupExpr);
}
}
if (!(source is Constant) && hash.Lookup (source_type, target, out o)) {
method = (MethodInfo) o;
} else {
- method = GetConversionOperator (null, source, target, look_for_explicit);
+ method = GetConversionOperator (RootContext.ToplevelTypes.Compiler, null, source, target, look_for_explicit);
if (!(source is Constant))
hash.Insert (source_type, target, method);
}
static public Expression ExplicitConversionStandard (ResolveContext ec, Expression expr,
Type target_type, Location l)
{
- int errors = Report.Errors;
+ int errors = ec.Report.Errors;
Expression ne = ImplicitConversionStandard (ec, expr, target_type, l);
- if (Report.Errors > errors)
+ if (ec.Report.Errors > errors)
return null;
if (ne != null)
// A counter to create new class names in interactive mode
static int class_count;
+
+ CompilerContext compiler;
%}
%token EOF
Report.FeatureIsNotAvailable (lt.Location, "external alias");
} else {
lt = (LocatedToken) $3;
- current_namespace.AddUsingExternalAlias (lt.Value, lt.Location);
+ current_namespace.AddUsingExternalAlias (lt.Value, lt.Location, Report);
}
}
| EXTERN_ALIAS error
$2 != TypeManager.system_int64_expr && $2 != TypeManager.system_uint64_expr &&
$2 != TypeManager.system_int16_expr && $2 != TypeManager.system_uint16_expr &&
$2 != TypeManager.system_byte_expr && $2 != TypeManager.system_sbyte_expr)
- Enum.Error_1008 (GetLocation ($2));
+ Enum.Error_1008 (GetLocation ($2), Report);
$$ = $2;
}
: type_expression_or_array
| VOID
{
- Expression.Error_VoidInvalidInTheContext (lexer.Location);
+ Expression.Error_VoidInvalidInTheContext (lexer.Location, Report);
$$ = TypeManager.system_void_expr;
}
;
: type_expression
| VOID
{
- Expression.Error_VoidInvalidInTheContext (lexer.Location);
+ Expression.Error_VoidInvalidInTheContext (lexer.Location, Report);
$$ = TypeManager.system_void_expr;
}
;
}
| VOID opt_rank_specifier
{
- Expression.Error_VoidInvalidInTheContext (lexer.Location);
+ Expression.Error_VoidInvalidInTheContext (lexer.Location, Report);
$$ = TypeManager.system_void_expr;
}
;
{
ExpressionStatement s = $1 as ExpressionStatement;
if (s == null) {
- ((Expression) $1).Error_InvalidExpressionStatement ();
+ Expression.Error_InvalidExpressionStatement (Report, GetLocation ($1));
s = EmptyExpressionStatement.Instance;
}
unsafe_statement
: UNSAFE
{
- RootContext.CheckUnsafeOption ((Location) $1);
+ RootContext.CheckUnsafeOption ((Location) $1, Report);
} block {
$$ = new Unsafe ((Block) $3);
}
: FROM_FIRST IDENTIFIER IN expression
{
$$ = new Linq.QueryExpression (current_block, new Linq.QueryStartClause ((Expression)$4));
- current_block = new Linq.QueryBlock (current_block, (LocatedToken) $2, GetLocation ($1));
+ current_block = new Linq.QueryBlock (compiler, current_block, (LocatedToken) $2, GetLocation ($1));
}
| FROM_FIRST type IDENTIFIER IN expression
{
$$ = new Linq.QueryExpression (current_block, new Linq.Cast ((FullNamedExpression)$2, (Expression)$5));
- current_block = new Linq.QueryBlock (current_block, (LocatedToken) $3, GetLocation ($1));
+ current_block = new Linq.QueryBlock (compiler, current_block, (LocatedToken) $3, GetLocation ($1));
}
;
: FROM IDENTIFIER IN expression
{
$$ = new Linq.QueryExpression (current_block, new Linq.QueryStartClause ((Expression)$4));
- current_block = new Linq.QueryBlock (current_block, (LocatedToken) $2, GetLocation ($1));
+ current_block = new Linq.QueryBlock (compiler, current_block, (LocatedToken) $2, GetLocation ($1));
}
| FROM type IDENTIFIER IN expression
{
$$ = new Linq.QueryExpression (current_block, new Linq.Cast ((FullNamedExpression)$2, (Expression)$5));
- current_block = new Linq.QueryBlock (current_block, (LocatedToken) $3, GetLocation ($1));
+ current_block = new Linq.QueryBlock (compiler, current_block, (LocatedToken) $3, GetLocation ($1));
}
;
from_clause
: FROM IDENTIFIER IN
{
- current_block = new Linq.QueryBlock (current_block, GetLocation ($1));
+ current_block = new Linq.QueryBlock (compiler, current_block, GetLocation ($1));
}
expression
{
}
| FROM type IDENTIFIER IN
{
- current_block = new Linq.QueryBlock (current_block, GetLocation ($1));
+ current_block = new Linq.QueryBlock (compiler, current_block, GetLocation ($1));
}
expression
{
select_or_group_clause
: SELECT
{
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
}
expression
{
if (linq_clause_blocks == null)
linq_clause_blocks = new Stack ();
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
linq_clause_blocks.Push (current_block);
}
expression
current_block.SetEndLocation (lexer.Location);
current_block = current_block.Parent;
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
}
BY expression
{
let_clause
: LET IDENTIFIER ASSIGN
{
- current_block = new Linq.QueryBlock (current_block, GetLocation ($1));
+ current_block = new Linq.QueryBlock (compiler, current_block, GetLocation ($1));
}
expression
{
where_clause
: WHERE
{
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
}
boolean_expression
{
if (linq_clause_blocks == null)
linq_clause_blocks = new Stack ();
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
linq_clause_blocks.Push (current_block);
}
expression ON
current_block.SetEndLocation (lexer.Location);
current_block = current_block.Parent;
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
linq_clause_blocks.Push (current_block);
}
expression EQUALS
current_block.SetEndLocation (lexer.Location);
current_block = current_block.Parent;
- current_block = new Linq.QueryBlock (current_block, (LocatedToken) $2, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, (LocatedToken) $2, lexer.Location);
}
expression opt_join_into
{
if (linq_clause_blocks == null)
linq_clause_blocks = new Stack ();
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
linq_clause_blocks.Push (current_block);
}
expression ON
current_block.SetEndLocation (lexer.Location);
current_block = current_block.Parent;
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
linq_clause_blocks.Push (current_block);
}
expression EQUALS
current_block.SetEndLocation (lexer.Location);
current_block = current_block.Parent;
- current_block = new Linq.QueryBlock (current_block, (LocatedToken) $3, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, (LocatedToken) $3, lexer.Location);
}
expression opt_join_into
{
orderby_clause
: ORDERBY
{
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
}
orderings
{
current_block.SetEndLocation (lexer.Location);
current_block = current_block.Parent;
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
}
orderings_then_by
{
current_block.SetEndLocation (lexer.Location);
current_block = current_block.Parent;
- current_block = new Linq.QueryBlock (current_block, lexer.Location);
+ current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
}
then_by
{
current_block.SetEndLocation (GetLocation ($1));
current_block = current_block.Parent;
- current_block = new Linq.QueryBlock (current_block, (LocatedToken) $2, GetLocation ($1));
+ current_block = new Linq.QueryBlock (compiler, current_block, (LocatedToken) $2, GetLocation ($1));
}
query_body
{
}
}
-static void Error_ExpectingTypeName (Expression expr)
+void Error_ExpectingTypeName (Expression expr)
{
if (expr is Invocation){
Report.Error (1002, expr.Location, "Expecting `;'");
} else {
- expr.Error_InvalidExpressionStatement ();
+ Expression.Error_InvalidExpressionStatement (Report, expr.Location);
}
}
-static void Error_ParameterModifierNotValid (string modifier, Location loc)
+void Error_ParameterModifierNotValid (string modifier, Location loc)
{
Report.Error (631, loc, "The parameter modifier `{0}' is not valid in this context",
modifier);
}
-static void Error_DuplicateParameterModifier (Location loc, Parameter.Modifier mod)
+void Error_DuplicateParameterModifier (Location loc, Parameter.Modifier mod)
{
Report.Error (1107, loc, "Duplicate parameter modifier `{0}'",
Parameter.GetModifierSignature (mod));
}
-static void Error_TypeExpected (Location loc)
+void Error_TypeExpected (Location loc)
{
Report.Error (1031, loc, "Type expected");
}
-static void Error_NamedArgumentExpected (NamedArgument a)
+void Error_NamedArgumentExpected (NamedArgument a)
{
Report.Error (1738, a.Name.Location, "Named arguments must appear after the positional arguments");
}
oob_stack = new Stack ();
}
-public CSharpParser (SeekableStreamReader reader, CompilationUnit file)
+public CSharpParser (SeekableStreamReader reader, CompilationUnit file, CompilerContext ctx)
{
if (RootContext.EvalMode)
undo = new Undo ();
this.file = file;
+ this.compiler = ctx;
current_namespace = new NamespaceEntry (null, file, null);
current_class = current_namespace.SlaveDeclSpace;
current_container = current_class.PartialContainer; // == RootContest.ToplevelTypes
oob_stack.Clear ();
- lexer = new Tokenizer (reader, file);
+ lexer = new Tokenizer (reader, file, ctx);
}
public void parse ()
throw new InternalErrorException ("who set it?");
}
-static void CheckToken (int error, int yyToken, string msg, Location loc)
+void CheckToken (int error, int yyToken, string msg, Location loc)
{
if (yyToken >= Token.FIRST_KEYWORD && yyToken <= Token.LAST_KEYWORD)
Report.Error (error, loc, "{0}: `{1}' is a keyword", msg, GetTokenName (yyToken));
return lexer.Location;
}
+Report Report {
+ get { return compiler.Report; }
+}
+
void start_block (Location loc)
{
if (current_block == null || parsing_anonymous_method) {
- current_block = new ToplevelBlock (current_block, current_local_parameters, current_generic_method, loc);
+ current_block = new ToplevelBlock (compiler, current_block, current_local_parameters, current_generic_method, loc);
parsing_anonymous_method = false;
} else {
current_block = new ExplicitBlock (current_block, loc, Location.Null);
SeekableStreamReader reader;
SourceFile ref_name;
CompilationUnit file_name;
+ CompilerContext context;
bool hidden = false;
int ref_line = 1;
int line = 1;
Report.FeatureIsNotAvailable (Location, "query expressions");
break;
case Token.VOID:
- Expression.Error_VoidInvalidInTheContext (Location);
+ Expression.Error_VoidInvalidInTheContext (Location, Report);
break;
default:
PopPosition ();
}
}
- public Tokenizer (SeekableStreamReader input, CompilationUnit file)
+ public Tokenizer (SeekableStreamReader input, CompilationUnit file, CompilerContext ctx)
{
this.ref_name = file;
this.file_name = file;
+ this.context = ctx;
reader = input;
putback_char = -1;
int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
foreach (int code in codes) {
if (code != 0)
- Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
+ Report.RegisterWarningRegion (Location).WarningDisable (Location, code, Report);
}
return;
}
Hashtable w_table = Report.warning_ignore_table;
foreach (int code in codes) {
if (w_table != null && w_table.Contains (code))
- Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
- Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
+ Report.Warning (1635, 1, Location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
+ Report.RegisterWarningRegion (Location).WarningEnable (Location, code, Report);
}
return;
}
return null;
}
+ Report Report {
+ get { return context.Report; }
+ }
+
void reset_doc_comment ()
{
xml_comment_buffer.Length = 0;
get { return (caching_flags & Flags.IsUsed) != 0; }
}
+ protected Report Report {
+ get {
+ return Compiler.Report;
+ }
+ }
+
public void SetMemberIsUsed ()
{
caching_flags |= Flags.IsUsed;
{
ObsoleteAttribute oa = GetObsoleteAttribute ();
if (oa != null)
- AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
+ AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, Report);
}
// Access level of a type.
internal virtual void GenerateDocComment (DeclSpace ds)
{
try {
- DocUtil.GenerateDocComment (this, ds);
+ DocUtil.GenerateDocComment (this, ds, Report);
} catch (Exception e) {
throw new InternalErrorException (this, e);
}
#region IMemberContext Members
+ public virtual CompilerContext Compiler {
+ get { return Parent.Module.Compiler; }
+ }
+
public virtual Type CurrentType {
get { return Parent.CurrentType; }
}
if (tp.Constraints == null)
continue;
- tp.Constraints.VerifyClsCompliance ();
+ tp.Constraints.VerifyClsCompliance (Report);
}
}
/// </summary>
///
// TODO: refactor as method is always 'this'
- public static void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
+ public static void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder, Report Report)
{
EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
}
}
- public bool CheckExistingMembersOverloads (MemberCore member, string name, ParametersCompiled parameters)
+ public bool CheckExistingMembersOverloads (MemberCore member, string name, ParametersCompiled parameters, Report Report)
{
ArrayList entries = (ArrayList)member_hash [name];
if (entries == null)
this.ReturnType = type;
ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
IsTopLevel ? Modifiers.INTERNAL :
- Modifiers.PRIVATE, name.Location);
+ Modifiers.PRIVATE, name.Location, Report);
Parameters = param_list;
}
CheckProtectedModifier ();
if (RootContext.StdLib && TypeManager.IsSpecialType (ret_type)) {
- Method.Error1599 (Location, ret_type);
+ Method.Error1599 (Location, ret_type, Report);
return false;
}
}
- public static ConstructorInfo GetConstructor (Type container_type, Type delegate_type)
+ public static ConstructorInfo GetConstructor (CompilerContext ctx, Type container_type, Type delegate_type)
{
Type dt = delegate_type;
Type[] g_args = null;
return d.ConstructorBuilder;
}
- Expression ml = Expression.MemberLookup (container_type,
+ Expression ml = Expression.MemberLookup (ctx, container_type,
null, dt, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, Location.Null);
MethodGroupExpr mg = ml as MethodGroupExpr;
if (mg == null) {
- Report.Error (-100, Location.Null, "Internal error: could not find delegate constructor!");
+ ctx.Report.Error (-100, Location.Null, "Internal error: could not find delegate constructor!");
// FIXME: null will cause a crash later
return null;
}
// Returns the MethodBase for "Invoke" from a delegate type, this is used
// to extract the signature of a delegate.
//
- public static MethodInfo GetInvokeMethod (Type container_type, Type delegate_type)
+ public static MethodInfo GetInvokeMethod (CompilerContext ctx, Type container_type, Type delegate_type)
{
Type dt = delegate_type;
return d.InvokeBuilder;
}
- Expression ml = Expression.MemberLookup (container_type, null, dt,
+ Expression ml = Expression.MemberLookup (ctx, container_type, null, dt,
"Invoke", Location.Null);
MethodGroupExpr mg = ml as MethodGroupExpr;
if (mg == null) {
- Report.Error (-100, Location.Null, "Internal error: could not find Invoke method!");
+ ctx.Report.Error (-100, Location.Null, "Internal error: could not find Invoke method!");
// FIXME: null will cause a crash later
return null;
}
else
arg_count = args.Count;
- MethodBase mb = GetInvokeMethod (ec.CurrentType, delegate_type);
+ MethodBase mb = GetInvokeMethod (ec.Compiler, ec.CurrentType, delegate_type);
MethodGroupExpr me = new MethodGroupExpr (new MemberInfo [] { mb }, delegate_type, loc);
AParametersCollection pd = TypeManager.GetParameterData (mb);
arg_count = args.Count;
if (!is_applicable && !params_method && arg_count != pd_count) {
- Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
+ ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
TypeManager.CSharpName (delegate_type), arg_count.ToString ());
return false;
}
public override Expression DoResolve (ResolveContext ec)
{
- constructor_method = Delegate.GetConstructor (ec.CurrentType, type);
+ constructor_method = Delegate.GetConstructor (ec.Compiler, ec.CurrentType, type);
- MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.CurrentType, type);
+ MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.Compiler, ec.CurrentType, type);
method_group.DelegateType = type;
method_group.CustomErrorHandler = this;
delegate_method = (MethodInfo) method_group;
if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
- Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
+ ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
TypeManager.GetFullNameSignature (delegate_method));
return null;
}
- Invocation.IsSpecialMethodInvocation (delegate_method, loc);
+ Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
if (emg != null) {
delegate_instance_expression = emg.ExtensionExpression;
Type e_type = delegate_instance_expression.Type;
if (TypeManager.IsValueType (e_type)) {
- Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
+ ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (e_type));
}
}
}
if (Invocation.IsMethodExcluded (delegate_method, loc)) {
- Report.SymbolRelatedToPreviousError (delegate_method);
+ ec.Report.SymbolRelatedToPreviousError (delegate_method);
MethodOrOperator m = TypeManager.GetMethod (delegate_method) as MethodOrOperator;
if (m != null && m.IsPartialDefinition) {
- Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
+ ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
TypeManager.CSharpSignature (delegate_method));
} else {
- Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
+ ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
TypeManager.CSharpSignature (delegate_method));
}
}
void Error_ConversionFailed (ResolveContext ec, MethodBase method, Expression return_type)
{
- MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.CurrentType, type);
+ MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.Compiler, ec.CurrentType, type);
string member_name = delegate_instance_expression != null ?
Delegate.FullDelegateDesc (method) :
TypeManager.GetFullNameSignature (method);
- Report.SymbolRelatedToPreviousError (type);
- Report.SymbolRelatedToPreviousError (method);
+ ec.Report.SymbolRelatedToPreviousError (type);
+ ec.Report.SymbolRelatedToPreviousError (method);
if (RootContext.Version == LanguageVersion.ISO_1) {
- Report.Error (410, loc, "A method or delegate `{0} {1}' parameters and return type must be same as delegate `{2} {3}' parameters and return type",
+ ec.Report.Error (410, loc, "A method or delegate `{0} {1}' parameters and return type must be same as delegate `{2} {3}' parameters and return type",
TypeManager.CSharpName (((MethodInfo) method).ReturnType), member_name,
TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
return;
}
if (return_type == null) {
- Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
+ ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
member_name, Delegate.FullDelegateDesc (invoke_method));
return;
}
- Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
+ ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
return_type.GetSignatureForError (), member_name,
TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
}
return false;
mg.DelegateType = target_type;
- MethodInfo invoke = Delegate.GetInvokeMethod (null, target_type);
+ MethodInfo invoke = Delegate.GetInvokeMethod (ec.Compiler, null, target_type);
Arguments arguments = CreateDelegateMethodArguments (TypeManager.GetParameterData (invoke), mg.Location);
return mg.OverloadResolve (ec, ref arguments, true, mg.Location) != null;
return true;
}
- public bool AmbiguousCall (MethodBase ambiguous)
+ public bool AmbiguousCall (ResolveContext ec, MethodBase ambiguous)
{
return false;
}
public override Expression DoResolve (ResolveContext ec)
{
if (Arguments == null || Arguments.Count != 1) {
- Error_InvalidDelegateArgument ();
+ ec.Report.Error (149, loc, "Method name expected");
return null;
}
method_group = e as MethodGroupExpr;
if (method_group == null) {
if (!TypeManager.IsDelegateType (e.Type)) {
- e.Error_UnexpectedKind (ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
+ e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
return null;
}
//
delegate_instance_expression = e;
method_group = new MethodGroupExpr (new MemberInfo [] {
- Delegate.GetInvokeMethod (ec.CurrentType, e.Type) }, e.Type, loc);
+ Delegate.GetInvokeMethod (ec.Compiler, ec.CurrentType, e.Type) }, e.Type, loc);
}
return base.DoResolve (ec);
}
-
- void Error_InvalidDelegateArgument ()
- {
- Report.Error (149, loc, "Method name expected");
- }
}
public class DelegateInvocation : ExpressionStatement {
Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
InstanceExpr.CreateExpressionTree (ec));
- return CreateExpressionFactoryCall ("Invoke", args);
+ return CreateExpressionFactoryCall (ec, "Invoke", args);
}
public override Expression DoResolve (ResolveContext ec)
{
if (InstanceExpr is EventExpr) {
- ((EventExpr) InstanceExpr).Error_CannotAssign ();
+ ((EventExpr) InstanceExpr).Error_CannotAssign (ec);
return null;
}
if (!Delegate.VerifyApplicability (ec, del_type, ref Arguments, loc))
return null;
- method = Delegate.GetInvokeMethod (ec.CurrentType, del_type);
+ method = Delegate.GetInvokeMethod (ec.Compiler, ec.CurrentType, del_type);
type = TypeManager.TypeToCoreType (method.ReturnType);
eclass = ExprClass.Value;
// handle warning report.
//
internal static void GenerateTypeDocComment (TypeContainer t,
- DeclSpace ds)
+ DeclSpace ds, Report Report)
{
- GenerateDocComment (t, ds);
+ GenerateDocComment (t, ds, Report);
if (t.DefaultStaticConstructor != null)
t.DefaultStaticConstructor.GenerateDocComment (t);
Environment.NewLine + " ";
private static XmlNode GetDocCommentNode (MemberCore mc,
- string name)
+ string name, Report Report)
{
// FIXME: It could be even optimizable as not
// to use XmlDocument. But anyways the nodes
// handle warning report.
//
internal static void GenerateDocComment (MemberCore mc,
- DeclSpace ds)
+ DeclSpace ds, Report Report)
{
if (mc.DocComment != null) {
string name = mc.GetDocCommentName (ds);
- XmlNode n = GetDocCommentNode (mc, name);
+ XmlNode n = GetDocCommentNode (mc, name, Report);
XmlElement el = n as XmlElement;
if (el != null) {
foreach (XmlNode inc in nl)
al.Add (inc);
foreach (XmlElement inc in al)
- if (!HandleInclude (mc, inc))
+ if (!HandleInclude (mc, inc, Report))
inc.ParentNode.RemoveChild (inc);
}
ds_target = ds;
foreach (XmlElement see in n.SelectNodes (".//see"))
- HandleSee (mc, ds_target, see);
+ HandleSee (mc, ds_target, see, Report);
foreach (XmlElement seealso in n.SelectNodes (".//seealso"))
- HandleSeeAlso (mc, ds_target, seealso);
+ HandleSeeAlso (mc, ds_target, seealso ,Report);
foreach (XmlElement see in n.SelectNodes (".//exception"))
- HandleException (mc, ds_target, see);
+ HandleException (mc, ds_target, see, Report);
}
n.WriteTo (RootContext.Documentation.XmlCommentOutput);
// Processes "include" element. Check included file and
// embed the document content inside this documentation node.
//
- private static bool HandleInclude (MemberCore mc, XmlElement el)
+ private static bool HandleInclude (MemberCore mc, XmlElement el, Report Report)
{
bool keep_include_node = false;
string file = el.GetAttribute ("file");
// Handles <see> elements.
//
private static void HandleSee (MemberCore mc,
- DeclSpace ds, XmlElement see)
+ DeclSpace ds, XmlElement see, Report r)
{
- HandleXrefCommon (mc, ds, see);
+ HandleXrefCommon (mc, ds, see, r);
}
//
// Handles <seealso> elements.
//
private static void HandleSeeAlso (MemberCore mc,
- DeclSpace ds, XmlElement seealso)
+ DeclSpace ds, XmlElement seealso, Report r)
{
- HandleXrefCommon (mc, ds, seealso);
+ HandleXrefCommon (mc, ds, seealso, r);
}
//
// Handles <exception> elements.
//
private static void HandleException (MemberCore mc,
- DeclSpace ds, XmlElement seealso)
+ DeclSpace ds, XmlElement seealso, Report r)
{
- HandleXrefCommon (mc, ds, seealso);
+ HandleXrefCommon (mc, ds, seealso, r);
}
static readonly char [] wsChars =
// returns a full runtime type name from a name which might
// be C# specific type name.
//
- private static Type FindDocumentedType (MemberCore mc, string name, DeclSpace ds, string cref)
+ private static Type FindDocumentedType (MemberCore mc, string name, DeclSpace ds, string cref, Report r)
{
bool is_array = false;
string identifier = name;
is_array = true;
}
}
- Type t = FindDocumentedTypeNonArray (mc, identifier, ds, cref);
+ Type t = FindDocumentedTypeNonArray (mc, identifier, ds, cref, r);
if (t != null && is_array)
t = Array.CreateInstance (t, 0).GetType ();
return t;
}
private static Type FindDocumentedTypeNonArray (MemberCore mc,
- string identifier, DeclSpace ds, string cref)
+ string identifier, DeclSpace ds, string cref, Report r)
{
switch (identifier) {
case "int":
if (index < 0)
return null;
int warn;
- Type parent = FindDocumentedType (mc, identifier.Substring (0, index), ds, cref);
+ Type parent = FindDocumentedType (mc, identifier.Substring (0, index), ds, cref, r);
if (parent == null)
return null;
// no need to detect warning 419 here
return FindDocumentedMember (mc, parent,
identifier.Substring (index + 1),
- null, ds, out warn, cref, false, null).Member as Type;
+ null, ds, out warn, cref, false, null, r).Member as Type;
}
private static MemberInfo [] empty_member_infos =
private static FoundMember FindDocumentedMember (MemberCore mc,
Type type, string member_name, Type [] param_list,
DeclSpace ds, out int warning_type, string cref,
- bool warn419, string name_for_error)
+ bool warn419, string name_for_error, Report r)
{
for (; type != null; type = type.DeclaringType) {
MemberInfo mi = FindDocumentedMemberNoNest (
mc, type, member_name, param_list, ds,
out warning_type, cref, warn419,
- name_for_error);
+ name_for_error, r);
if (mi != null)
return new FoundMember (type, mi);
}
private static MemberInfo FindDocumentedMemberNoNest (
MemberCore mc, Type type, string member_name,
Type [] param_list, DeclSpace ds, out int warning_type,
- string cref, bool warn419, string name_for_error)
+ string cref, bool warn419, string name_for_error, Report Report)
{
warning_type = 0;
MemberInfo [] mis;
if (mis == null || mis.Length == 0)
return null;
if (warn419 && IsAmbiguous (mis))
- Report419 (mc, name_for_error, mis);
+ Report419 (mc, name_for_error, mis, Report);
return mis [0];
}
if (warn419 && mis.Length > 0) {
if (IsAmbiguous (mis))
- Report419 (mc, name_for_error, mis);
+ Report419 (mc, name_for_error, mis, Report);
return mis [0];
}
((PropertyInfo) mi).PropertyType :
null;
if (return_type_name != null) {
- Type returnType = FindDocumentedType (mc, return_type_name, ds, cref);
+ Type returnType = FindDocumentedType (mc, return_type_name, ds, cref, Report);
if (returnType == null || returnType != expected) {
warning_type = 1581;
Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref);
// Checks cref attribute.
//
private static void HandleXrefCommon (MemberCore mc,
- DeclSpace ds, XmlElement xref)
+ DeclSpace ds, XmlElement xref, Report Report)
{
string cref = xref.GetAttribute ("cref").Trim (wsChars);
// when, XmlReader, "if (cref == null)"
name = signature;
parameters = null;
}
- Normalize (mc, ref name);
+ Normalize (mc, ref name, Report);
string identifier = GetBodyIdentifierFromName (name);
for (int i = 0; i < name_elems.Length; i++) {
string nameElem = GetBodyIdentifierFromName (name_elems [i]);
if (i > 0)
- Normalize (mc, ref nameElem);
+ Normalize (mc, ref nameElem, Report);
if (!Tokenizer.IsValidIdentifier (nameElem)
&& nameElem.IndexOf ("operator") < 0) {
Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
ArrayList plist = new ArrayList ();
for (int i = 0; i < param_list.Length; i++) {
string param_type_name = param_list [i].Trim (wsChars);
- Normalize (mc, ref param_type_name);
- Type param_type = FindDocumentedType (mc, param_type_name, ds, cref);
+ Normalize (mc, ref param_type_name, Report);
+ Type param_type = FindDocumentedType (mc, param_type_name, ds, cref, Report);
if (param_type == null) {
Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'",
(i + 1).ToString (), cref);
parameter_types = plist.ToArray (typeof (Type)) as Type [];
}
- Type type = FindDocumentedType (mc, name, ds, cref);
+ Type type = FindDocumentedType (mc, name, ds, cref, Report);
if (type != null
// delegate must not be referenced with args
&& (!TypeManager.IsDelegateType (type)
if (period > 0) {
string typeName = name.Substring (0, period);
string member_name = name.Substring (period + 1);
- Normalize (mc, ref member_name);
- type = FindDocumentedType (mc, typeName, ds, cref);
+ Normalize (mc, ref member_name, Report);
+ type = FindDocumentedType (mc, typeName, ds, cref, Report);
int warn_result;
if (type != null) {
- FoundMember fm = FindDocumentedMember (mc, type, member_name, parameter_types, ds, out warn_result, cref, true, name);
+ FoundMember fm = FindDocumentedMember (mc, type, member_name, parameter_types, ds, out warn_result, cref, true, name, Report);
if (warn_result > 0)
return;
if (!fm.IsEmpty) {
}
else {
int warn_result;
- FoundMember fm = FindDocumentedMember (mc, ds.TypeBuilder, name, parameter_types, ds, out warn_result, cref, true, name);
+ FoundMember fm = FindDocumentedMember (mc, ds.TypeBuilder, name, parameter_types, ds, out warn_result, cref, true, name, Report);
if (warn_result > 0)
return;
if (!fm.IsEmpty) {
return identifier;
}
- static void Report419 (MemberCore mc, string member_name, MemberInfo [] mis)
+ static void Report419 (MemberCore mc, string member_name, MemberInfo [] mis, Report Report)
{
Report.Warning (419, 3, mc.Location,
"Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched",
// that means removal of DOM use.
//
internal static void OnMethodGenerateDocComment (
- MethodCore mc, XmlElement el)
+ MethodCore mc, XmlElement el, Report Report)
{
Hashtable paramTags = new Hashtable ();
foreach (XmlElement pelem in el.SelectNodes ("param")) {
}
}
- private static void Normalize (MemberCore mc, ref string name)
+ private static void Normalize (MemberCore mc, ref string name, Report Report)
{
if (name.Length > 0 && name [0] == '@')
name = name.Substring (1);
//
// Outputs XML documentation comment from tokenized comments.
//
- public bool OutputDocComment (string asmfilename)
+ public bool OutputDocComment (string asmfilename, Report Report)
{
XmlTextWriter w = null;
try {
w.WriteEndElement (); // assembly
w.WriteStartElement ("members");
XmlCommentOutput = w;
- GenerateDocComment ();
+ GenerateDocComment (Report);
w.WriteFullEndElement (); // members
w.WriteEndElement ();
w.WriteWhitespace (Environment.NewLine);
//
// Fixes full type name of each documented types/members up.
//
- public void GenerateDocComment ()
+ public void GenerateDocComment (Report r)
{
TypeContainer root = RootContext.ToplevelTypes;
if (root.Types != null)
foreach (TypeContainer tc in root.Types)
- DocUtil.GenerateTypeDocComment (tc, null);
+ DocUtil.GenerateTypeDocComment (tc, null, r);
if (root.Delegates != null)
foreach (Delegate d in root.Delegates)
- DocUtil.GenerateDocComment (d, null);
+ DocUtil.GenerateDocComment (d, null, r);
}
}
}
//
Encoding encoding;
+ readonly CompilerContext ctx;
+
static readonly char[] argument_value_separator = new char [] { ';', ',' };
static public void Reset ()
output_file = null;
}
- public Driver ()
+ private Driver (CompilerContext ctx)
{
+ this.ctx = ctx;
encoding = Encoding.Default;
}
- public static Driver Create (string [] args, bool require_files)
+ public static Driver Create (string[] args, bool require_files, ReportPrinter printer)
{
- Driver d = new Driver ();
+ Driver d = new Driver (new CompilerContext (new Report (printer)));
+
if (!d.ParseArguments (args, require_files))
return null;
return d;
}
+ Report Report {
+ get { return ctx.Report; }
+ }
+
void ShowTime (string msg)
{
if (!timestamps)
(int) span.TotalSeconds, span.Milliseconds, msg);
}
- void tokenize_file (CompilationUnit file)
+ void tokenize_file (CompilationUnit file, CompilerContext ctx)
{
Stream input;
using (input){
SeekableStreamReader reader = new SeekableStreamReader (input, encoding);
- Tokenizer lexer = new Tokenizer (reader, file);
+ Tokenizer lexer = new Tokenizer (reader, file, ctx);
int token, tokens = 0, errors = 0;
while ((token = lexer.token ()) != Token.EOF){
void Parse (SeekableStreamReader reader, CompilationUnit file)
{
- CSharpParser parser = new CSharpParser (reader, file);
- parser.ErrorOutput = Report.Stderr;
+ CSharpParser parser = new CSharpParser (reader, file, ctx);
try {
parser.parse ();
} catch (Exception ex) {
"Options can be of the form -option or /option");
}
- static void TargetUsage ()
+ void TargetUsage ()
{
Report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
}
{
Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
- Driver d = Driver.Create (args, true);
+ Driver d = Driver.Create (args, true, new ConsoleReportPrinter ());
if (d == null)
return 1;
- if (d.Compile () && Report.Errors == 0) {
- if (Report.Warnings > 0) {
- Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
+ if (d.Compile () && d.Report.Errors == 0) {
+ if (d.Report.Warnings > 0) {
+ Console.WriteLine ("Compilation succeeded - {0} warning(s)", d.Report.Warnings);
}
Environment.Exit (0);
return 0;
Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
- Report.Errors, Report.Warnings);
+ d.Report.Errors, d.Report.Warnings);
Environment.Exit (1);
return 1;
}
- static public void LoadAssembly (string assembly, bool soft)
+ public void LoadAssembly (string assembly, bool soft)
{
LoadAssembly (assembly, null, soft);
}
- static void Error6 (string name, string log)
+ void Error6 (string name, string log)
{
if (log != null && log.Length > 0)
Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
Report.Error (6, "cannot find metadata file `{0}'", name);
}
- static void Error9 (string type, string filename, string log)
+ void Error9 (string type, string filename, string log)
{
if (log != null && log.Length > 0)
Report.ExtraInformation (Location.Null, "Log:\n" + log + "\n(log related to previous ");
Report.Error (9, "file `{0}' has invalid `{1}' metadata", filename, type);
}
- static void BadAssembly (string filename, string log)
+ void BadAssembly (string filename, string log)
{
MethodInfo adder_method = AssemblyClass.AddModule_Method;
Error9 ("assembly", filename, log);
}
- static public void LoadAssembly (string assembly, string alias, bool soft)
+ public void LoadAssembly (string assembly, string alias, bool soft)
{
Assembly a = null;
string total_log = "";
if (alias == null)
GlobalRootNamespace.Instance.AddAssemblyReference (a);
else
- GlobalRootNamespace.Instance.DefineRootNamespace (alias, a);
+ GlobalRootNamespace.Instance.DefineRootNamespace (alias, a, ctx);
} catch (BadImageFormatException f) {
// .NET 2.0 throws this if we try to load a module without an assembly manifest ...
}
}
- static public void LoadModule (string module)
+ public void LoadModule (string module)
{
Module m = null;
string total_log = "";
foreach (DictionaryEntry entry in external_aliases)
LoadAssembly ((string) entry.Value, (string) entry.Key, false);
- GlobalRootNamespace.Instance.ComputeNamespaces ();
+ GlobalRootNamespace.Instance.ComputeNamespaces (ctx);
}
static string [] LoadArgs (string file)
if (first_source == null)
first_source = f;
- Location.AddFile (f);
+ Location.AddFile (Report, f);
}
bool ParseArguments (string[] args, bool require_files)
ArrayList cu = Location.SourceFiles;
for (int i = 0; i < cu.Count; ++i) {
if (tokenize) {
- tokenize_file ((CompilationUnit) cu [i]);
+ tokenize_file ((CompilationUnit) cu [i], ctx);
} else {
Parse ((CompilationUnit) cu [i]);
}
}
}
- static void SetWarningLevel (string s)
+ void SetWarningLevel (string s)
{
int level = -1;
return true;
case "--stacktrace":
- Report.Stacktrace = true;
+ Report.Printer.Stacktrace = true;
return true;
case "--linkresource":
Environment.Exit (1);
}
if (embedded_resources == null)
- embedded_resources = new Resources ();
+ embedded_resources = new Resources (ctx);
embedded_resources.Add (false, args [++i], args [i]);
return true;
Environment.Exit (1);
}
if (embedded_resources == null)
- embedded_resources = new Resources ();
+ embedded_resources = new Resources (ctx);
embedded_resources.Add (true, args [++i], args [i]);
return true;
}
#if !SMCS_SOURCE
- public static string GetPackageFlags (string packages, bool fatal)
+ public static string GetPackageFlags (string packages, bool fatal, Report report)
{
ProcessStartInfo pi = new ProcessStartInfo ();
pi.FileName = "pkg-config";
try {
p = Process.Start (pi);
} catch (Exception e) {
- Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
+ report.Error (-27, "Couldn't run pkg-config: " + e.Message);
if (fatal)
Environment.Exit (1);
p.Close ();
}
if (p.StandardOutput == null){
- Report.Warning (-27, 1, "Specified package did not return any information");
+ report.Warning (-27, 1, "Specified package did not return any information");
p.Close ();
return null;
}
string pkgout = p.StandardOutput.ReadToEnd ();
p.WaitForExit ();
if (p.ExitCode != 0) {
- Report.Error (-27, "Error running pkg-config. Check the above output.");
+ report.Error (-27, "Error running pkg-config. Check the above output.");
if (fatal)
Environment.Exit (1);
p.Close ();
Environment.Exit (1);
}
packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
- string pkgout = GetPackageFlags (packages, true);
+ string pkgout = GetPackageFlags (packages, true, Report);
if (pkgout != null){
string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
case "/res":
case "/resource":
if (embedded_resources == null)
- embedded_resources = new Resources ();
+ embedded_resources = new Resources (ctx);
bool embeded = arg [1] == 'r' || arg [1] == 'R';
string[] s = value.Split (argument_value_separator);
return false;
}
- static void Error_WrongOption (string option)
+ void Error_WrongOption (string option)
{
Report.Error (2007, "Unrecognized command-line option: `{0}'", option);
}
public bool Compile ()
{
// TODO: Should be passed to parser as an argument
- RootContext.ToplevelTypes = new ModuleContainer (RootContext.Unsafe);
+ RootContext.ToplevelTypes = new ModuleContainer (ctx, RootContext.Unsafe);
Parse ();
if (Report.Errors > 0)
output_file = first_source + RootContext.TargetExt;
}
- if (!CodeGen.Init (output_file, output_file, want_debugging_support))
+ if (!CodeGen.Init (output_file, output_file, want_debugging_support, ctx))
return false;
if (RootContext.Target == Target.Module) {
if (timestamps)
ShowTime ("References loaded");
- if (!TypeManager.InitCoreTypes () || Report.Errors > 0)
+ if (!TypeManager.InitCoreTypes (ctx) || Report.Errors > 0)
return false;
- TypeManager.InitOptionalCoreTypes ();
+ TypeManager.InitOptionalCoreTypes (ctx);
if (timestamps)
ShowTime (" Core Types done");
if (Report.Errors == 0 &&
RootContext.Documentation != null &&
!RootContext.Documentation.OutputDocComment (
- output_file))
+ output_file, Report))
return false;
//
if (RootContext.VerifyClsCompliance) {
if (CodeGen.Assembly.IsClsCompliant) {
- AttributeTester.VerifyModulesClsCompliance ();
+ AttributeTester.VerifyModulesClsCompliance (ctx);
TypeManager.LoadAllImportedTypes ();
}
}
if (Report.Errors > 0)
return false;
- CodeGen.Save (output_file, want_debugging_support);
+ CodeGen.Save (output_file, want_debugging_support, Report);
if (timestamps) {
ShowTime ("Saved output");
ShowTotalTime ("Total");
}
Timer.ShowTimers ();
-
- if (Report.ExpectedError != 0) {
- if (Report.Errors == 0) {
- Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
- "No other errors reported.");
-
- Environment.Exit (2);
- } else {
- Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
- "However, other errors were reported.");
-
- Environment.Exit (1);
- }
-
-
- return false;
- }
#if DEBUGME
Console.WriteLine ("Size of strings held: " + DeclSpace.length);
null, CallingConventions.Any, argst, null);
if (embed_res == null) {
- Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
+ RootContext.ToplevelTypes.Compiler.Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
}
}
IDictionary embedded_resources = new HybridDictionary ();
+ readonly CompilerContext ctx;
+
+ public Resources (CompilerContext ctx)
+ {
+ this.ctx = ctx;
+ }
public void Add (bool embeded, string file, string name)
{
public void Add (bool embeded, string file, string name, bool isPrivate)
{
if (embedded_resources.Contains (name)) {
- Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
+ ctx.Report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", name);
return;
}
IResource r = embeded ?
{
foreach (IResource r in embedded_resources.Values) {
if (!File.Exists (r.FileName)) {
- Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
+ ctx.Report.Error (1566, "Error reading resource file `{0}'", r.FileName);
continue;
}
public class CompilerCallableEntryPoint : MarshalByRefObject {
public static bool InvokeCompiler (string [] args, TextWriter error)
{
- Report.Stderr = error;
try {
- Driver d = Driver.Create (args, true);
+ StreamReportPrinter srp = new StreamReportPrinter (error);
+ Driver d = Driver.Create (args, true, srp);
if (d == null)
return false;
- return d.Compile () && Report.Errors == 0;
- }
- finally {
- Report.Stderr = Console.Error;
+ return d.Compile () && srp.ErrorsCount == 0;
+ } finally {
Reset ();
}
}
Driver.Reset ();
RootContext.Reset (full_flag);
Location.Reset ();
- Report.Reset ();
TypeManager.Reset ();
PredefinedAttributes.Reset ();
TypeHandle.Reset ();
return this;
}
}
+/*
+ public class RuntimeExpression : Expression
+ {
+ public RuntimeExpression (Type type)
+ {
+ this.type = type;
+ this.eclass = ExprClass.Value;
+ }
+
+ public override Expression CreateExpressionTree (ResolveContext ec)
+ {
+ throw new NotImplementedException ();
+ }
+ public override Expression DoResolve (ResolveContext ec)
+ {
+ return this;
+ }
+
+ public override void Emit (EmitContext ec)
+ {
+ throw new NotImplementedException ();
+ }
+ }
+*/
interface IDynamicBinder
{
Expression CreateCallSiteBinder (ResolveContext ec, Arguments args);
public override Expression DoResolve (ResolveContext ec)
{
if (TypeManager.call_site_type == null)
- TypeManager.call_site_type = TypeManager.CoreLookupType (
+ TypeManager.call_site_type = TypeManager.CoreLookupType (ec.Compiler,
"System.Runtime.CompilerServices", "CallSite", Kind.Class, true);
if (TypeManager.generic_call_site_type == null)
- TypeManager.generic_call_site_type = TypeManager.CoreLookupType (
+ TypeManager.generic_call_site_type = TypeManager.CoreLookupType (ec.Compiler,
"System.Runtime.CompilerServices", "CallSite`1", Kind.Class, true);
eclass = ExprClass.Value;
void EmitCall (EmitContext ec, bool isStatement)
{
int dyn_args_count = arguments == null ? 0 : arguments.Count;
- TypeExpr site_type = CreateSiteType (isStatement, dyn_args_count);
+ TypeExpr site_type = CreateSiteType (RootContext.ToplevelTypes.Compiler, isStatement, dyn_args_count);
FieldExpr site_field_expr = new FieldExpr (CreateSiteField (site_type).FieldBuilder, loc);
SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "Microsoft", loc), "CSharp", loc), "RuntimeBinder", loc);
}
- TypeExpr CreateSiteType (bool isStatement, int dyn_args_count)
+ TypeExpr CreateSiteType (CompilerContext ctx, bool isStatement, int dyn_args_count)
{
int default_args = isStatement ? 1 : 2;
if (!has_ref_out_argument) {
string d_name = isStatement ? "Action`" : "Func`";
- Type t = TypeManager.CoreLookupType ("System", d_name + (dyn_args_count + default_args), Kind.Delegate, false);
+ Type t = TypeManager.CoreLookupType (ctx, "System", d_name + (dyn_args_count + default_args), Kind.Delegate, false);
if (t != null) {
if (!isStatement)
targs[targs.Length - 1] = new TypeExpression (TypeManager.TypeToReflectionType (type), loc);
public virtual bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
{
- Attribute.Error_AttributeArgumentNotValid (loc);
+ Attribute.Error_AttributeArgumentNotValid (ec, loc);
value = null;
return false;
}
public virtual FullNamedExpression ResolveAsTypeStep (IMemberContext rc, bool silent)
{
if (!silent) {
- Expression e = Resolve (new ResolveContext (rc));
+ ResolveContext ec = new ResolveContext (rc);
+ Expression e = Resolve (ec);
if (e != null)
- e.Error_UnexpectedKind (ResolveFlags.Type, loc);
+ e.Error_UnexpectedKind (ec, ResolveFlags.Type, loc);
}
return null;
if (!silent) { // && !(te is TypeParameterExpr)) {
ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (te.Type);
if (obsolete_attr != null && !ec.IsObsolete) {
- AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location);
+ AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location, ec.Compiler.Report);
}
}
public TypeExpr ResolveAsBaseTerminal (IMemberContext ec, bool silent)
{
- int errors = Report.Errors;
+ int errors = ec.Compiler.Report.Errors;
FullNamedExpression fne = ResolveAsTypeStep (ec, silent);
TypeExpr te = fne as TypeExpr;
if (te == null) {
- if (!silent && errors == Report.Errors)
- fne.Error_UnexpectedKind (null, "type", loc);
+ if (!silent && errors == ec.Compiler.Report.Errors)
+ fne.Error_UnexpectedKind (ec.Compiler.Report, null, "type", loc);
return null;
}
if (!te.CheckAccessLevel (ec)) {
- Report.SymbolRelatedToPreviousError (te.Type);
- ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
+ ec.Compiler.Report.SymbolRelatedToPreviousError (te.Type);
+ ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type), ec.Compiler.Report);
return null;
}
return te;
}
- public static void ErrorIsInaccesible (Location loc, string name)
+ public static void ErrorIsInaccesible (Location loc, string name, Report Report)
{
Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
}
- protected static void Error_CannotAccessProtected (Location loc, MemberInfo m, Type qualifier, Type container)
+ protected static void Error_CannotAccessProtected (ResolveContext ec, Location loc, MemberInfo m, Type qualifier, Type container)
{
- Report.Error (1540, loc, "Cannot access protected member `{0}' via a qualifier of type `{1}'."
+ ec.Report.Error (1540, loc, "Cannot access protected member `{0}' via a qualifier of type `{1}'."
+ " The qualifier must be of type `{2}' or derived from it",
TypeManager.GetFullNameSignature (m),
TypeManager.CSharpName (qualifier),
}
- public static void Error_InvalidExpressionStatement (Location loc)
+ public static void Error_InvalidExpressionStatement (Report Report, Location loc)
{
Report.Error (201, loc, "Only assignment, call, increment, decrement, and new object " +
"expressions can be used as a statement");
}
- public void Error_InvalidExpressionStatement ()
+ public void Error_InvalidExpressionStatement (BlockContext ec)
{
- Error_InvalidExpressionStatement (loc);
+ Error_InvalidExpressionStatement (ec.Report, loc);
}
- protected void Error_CannotAssign (string to, string roContext)
- {
- Report.Error (1656, loc, "Cannot assign to `{0}' because it is a `{1}'",
- to, roContext);
- }
-
- public static void Error_VoidInvalidInTheContext (Location loc)
+ public static void Error_VoidInvalidInTheContext (Location loc, Report Report)
{
Report.Error (1547, loc, "Keyword `void' cannot be used in this context");
}
string sig2 = target.DeclaringMethod == null ?
TypeManager.CSharpName (target.DeclaringType) :
TypeManager.CSharpSignature (target.DeclaringMethod);
- Report.ExtraInformation (loc,
+ ec.Report.ExtraInformation (loc,
String.Format (
"The generic parameter `{0}' of `{1}' cannot be converted to the generic parameter `{0}' of `{2}' (in the previous ",
Type.Name, sig1, sig2));
#endif
} else if (Type.FullName == target.FullName){
- Report.ExtraInformation (loc,
+ ec.Report.ExtraInformation (loc,
String.Format (
"The type `{0}' has two conflicting definitions, one comes from `{1}' and the other from `{2}' (in the previous ",
Type.FullName, Type.Assembly.FullName, target.Assembly.FullName));
}
if (expl) {
- Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
+ ec.Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
TypeManager.CSharpName (type), TypeManager.CSharpName (target));
return;
}
- Report.DisableReporting ();
+ ec.Report.DisableReporting ();
bool expl_exists = Convert.ExplicitConversion (ec, this, target, Location.Null) != null;
- Report.EnableReporting ();
+ ec.Report.EnableReporting ();
if (expl_exists) {
- Report.Error (266, loc, "Cannot implicitly convert type `{0}' to `{1}'. " +
+ ec.Report.Error (266, loc, "Cannot implicitly convert type `{0}' to `{1}'. " +
"An explicit conversion exists (are you missing a cast?)",
TypeManager.CSharpName (Type), TypeManager.CSharpName (target));
return;
}
- Report.Error (29, loc, "Cannot implicitly convert type `{0}' to `{1}'",
+ ec.Report.Error (29, loc, "Cannot implicitly convert type `{0}' to `{1}'",
TypeManager.CSharpName (type),
TypeManager.CSharpName (target));
}
- public virtual void Error_VariableIsUsedBeforeItIsDeclared (string name)
+ public virtual void Error_VariableIsUsedBeforeItIsDeclared (Report Report, string name)
{
Report.Error (841, loc, "A local variable `{0}' cannot be used before it is declared", name);
}
- protected virtual void Error_TypeDoesNotContainDefinition (Type type, string name)
+ protected virtual void Error_TypeDoesNotContainDefinition (ResolveContext ec, Type type, string name)
{
- Error_TypeDoesNotContainDefinition (loc, type, name);
+ Error_TypeDoesNotContainDefinition (ec, loc, type, name);
}
- public static void Error_TypeDoesNotContainDefinition (Location loc, Type type, string name)
+ public static void Error_TypeDoesNotContainDefinition (ResolveContext ec, Location loc, Type type, string name)
{
- Report.SymbolRelatedToPreviousError (type);
- Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
+ ec.Report.SymbolRelatedToPreviousError (type);
+ ec.Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
TypeManager.CSharpName (type), name);
}
- protected static void Error_ValueAssignment (Location loc)
+ protected static void Error_ValueAssignment (ResolveContext ec, Location loc)
{
- Report.Error (131, loc, "The left-hand side of an assignment must be a variable, a property or an indexer");
+ ec.Report.Error (131, loc, "The left-hand side of an assignment must be a variable, a property or an indexer");
}
ResolveFlags ExprClassToResolveFlags
return null;
if ((flags & e.ExprClassToResolveFlags) == 0) {
- e.Error_UnexpectedKind (flags, loc);
+ e.Error_UnexpectedKind (ec, flags, loc);
return null;
}
Expression e = Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
if (e != null && e.eclass == ExprClass.MethodGroup && RootContext.Version == LanguageVersion.ISO_1) {
- ((MethodGroupExpr) e).ReportUsageError ();
+ ((MethodGroupExpr) e).ReportUsageError (ec);
return null;
}
return e;
return c;
if (type != null && TypeManager.IsReferenceType (type))
- Const.Error_ConstantCanBeInitializedWithNullOnly (type, loc, mc.GetSignatureForError ());
+ Const.Error_ConstantCanBeInitializedWithNullOnly (type, loc, mc.GetSignatureForError (), ec.Report);
else
- Const.Error_ExpressionMustBeConstant (loc, mc.GetSignatureForError ());
+ Const.Error_ExpressionMustBeConstant (loc, mc.GetSignatureForError (), ec.Report);
return null;
}
/// </remarks>
public Expression ResolveLValue (ResolveContext ec, Expression right_side)
{
- int errors = Report.Errors;
+ int errors = ec.Report.Errors;
bool out_access = right_side == EmptyExpression.OutAccess;
Expression e = DoResolveLValue (ec, right_side);
}
if (e == null) {
- if (errors == Report.Errors) {
+ if (errors == ec.Report.Errors) {
if (out_access)
- Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
+ ec.Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
else
- Error_ValueAssignment (loc);
+ Error_ValueAssignment (ec, loc);
}
return null;
}
// FIXME: Potential optimization, have a static ArrayList
//
- public static Expression MemberLookup (Type container_type, Type queried_type, string name,
+ public static Expression MemberLookup (CompilerContext ctx, Type container_type, Type queried_type, string name,
MemberTypes mt, BindingFlags bf, Location loc)
{
- return MemberLookup (container_type, null, queried_type, name, mt, bf, loc);
+ return MemberLookup (ctx, container_type, null, queried_type, name, mt, bf, loc);
}
//
// `qualifier_type' or null to lookup members in the current class.
//
- public static Expression MemberLookup (Type container_type,
+ public static Expression MemberLookup (CompilerContext ctx, Type container_type,
Type qualifier_type, Type queried_type,
string name, MemberTypes mt,
BindingFlags bf, Location loc)
}
if (methods.Count == 0 && non_methods != null && non_methods.Count > 1) {
- Report.SymbolRelatedToPreviousError ((MemberInfo)non_methods [1]);
- Report.SymbolRelatedToPreviousError ((MemberInfo)non_methods [0]);
- Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
+ ctx.Report.SymbolRelatedToPreviousError ((MemberInfo)non_methods [1]);
+ ctx.Report.SymbolRelatedToPreviousError ((MemberInfo)non_methods [0]);
+ ctx.Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
TypeManager.GetFullNameSignature ((MemberInfo)non_methods [1]),
TypeManager.GetFullNameSignature ((MemberInfo)non_methods [0]));
return null;
MemberInfo non_method = (MemberInfo) non_methods [0];
if (method.DeclaringType == non_method.DeclaringType) {
// Cannot happen with C# code, but is valid in IL
- Report.SymbolRelatedToPreviousError (method);
- Report.SymbolRelatedToPreviousError (non_method);
- Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
+ ctx.Report.SymbolRelatedToPreviousError (method);
+ ctx.Report.SymbolRelatedToPreviousError (non_method);
+ ctx.Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
TypeManager.GetFullNameSignature (non_method),
TypeManager.CSharpSignature (method));
return null;
}
if (is_interface) {
- Report.SymbolRelatedToPreviousError (method);
- Report.SymbolRelatedToPreviousError (non_method);
- Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and non-method `{1}'. Using method `{0}'",
+ ctx.Report.SymbolRelatedToPreviousError (method);
+ ctx.Report.SymbolRelatedToPreviousError (non_method);
+ ctx.Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and non-method `{1}'. Using method `{0}'",
TypeManager.CSharpSignature (method), TypeManager.GetFullNameSignature (non_method));
}
}
BindingFlags.Static |
BindingFlags.Instance;
- public static Expression MemberLookup (Type container_type, Type queried_type,
+ public static Expression MemberLookup (CompilerContext ctx, Type container_type, Type queried_type,
string name, Location loc)
{
- return MemberLookup (container_type, null, queried_type, name,
+ return MemberLookup (ctx, container_type, null, queried_type, name,
AllMemberTypes, AllBindingFlags, loc);
}
- public static Expression MemberLookup (Type container_type, Type qualifier_type,
+ public static Expression MemberLookup (CompilerContext ctx, Type container_type, Type qualifier_type,
Type queried_type, string name, Location loc)
{
- return MemberLookup (container_type, qualifier_type, queried_type,
+ return MemberLookup (ctx, container_type, qualifier_type, queried_type,
name, AllMemberTypes, AllBindingFlags, loc);
}
- public static MethodGroupExpr MethodLookup (Type container_type, Type queried_type,
+ public static MethodGroupExpr MethodLookup (CompilerContext ctx, Type container_type, Type queried_type,
string name, Location loc)
{
- return (MethodGroupExpr)MemberLookup (container_type, null, queried_type, name,
+ return (MethodGroupExpr)MemberLookup (ctx, container_type, null, queried_type, name,
MemberTypes.Method, AllBindingFlags, loc);
}
{
Expression e;
- int errors = Report.Errors;
- e = MemberLookup (ec.CurrentType, qualifier_type, queried_type, name, mt, bf, loc);
+ int errors = ec.Report.Errors;
+ e = MemberLookup (ec.Compiler, ec.CurrentType, qualifier_type, queried_type, name, mt, bf, loc);
- if (e != null || errors != Report.Errors)
+ if (e != null || errors != ec.Report.Errors)
return e;
// No errors were reported by MemberLookup, but there was an error.
- return Error_MemberLookupFailed (ec.CurrentType, qualifier_type, queried_type,
+ return Error_MemberLookupFailed (ec, ec.CurrentType, qualifier_type, queried_type,
name, null, mt, bf);
}
- protected virtual Expression Error_MemberLookupFailed (Type container_type, Type qualifier_type,
+ protected virtual Expression Error_MemberLookupFailed (ResolveContext ec, Type container_type, Type qualifier_type,
Type queried_type, string name, string class_name,
MemberTypes mt, BindingFlags bf)
{
name, null);
if (lookup != null) {
- Expression e = Error_MemberLookupFailed (queried_type, lookup);
+ Expression e = Error_MemberLookupFailed (ec, queried_type, lookup);
//
// FIXME: This is still very wrong, it should be done inside
//
if (e == null || (mt & (MemberTypes.Method | MemberTypes.Constructor)) == 0) {
MemberInfo mi = lookup[0];
- Report.SymbolRelatedToPreviousError (mi);
+ ec.Report.SymbolRelatedToPreviousError (mi);
if (qualifier_type != null && container_type != null && qualifier_type != container_type &&
TypeManager.IsNestedFamilyAccessible (container_type, mi.DeclaringType)) {
// Although a derived class can access protected members of
// base class (CS1540). If the qualifier_type is a base of the
// ec.CurrentType and the lookup succeeds with the latter one,
// then we are in this situation.
- Error_CannotAccessProtected (loc, mi, qualifier_type, container_type);
+ Error_CannotAccessProtected (ec, loc, mi, qualifier_type, container_type);
} else {
- ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (mi));
+ ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (mi), ec.Report);
}
}
if (lookup == null) {
if (class_name != null) {
- Report.Error (103, loc, "The name `{0}' does not exist in the current context",
+ ec.Report.Error (103, loc, "The name `{0}' does not exist in the current context",
name);
} else {
- Error_TypeDoesNotContainDefinition (queried_type, name);
+ Error_TypeDoesNotContainDefinition (ec, queried_type, name);
}
return null;
}
if ((lookup.Length == 1) && (lookup [0] is Type)) {
Type t = (Type) lookup [0];
- Report.Error (305, loc,
+ ec.Report.Error (305, loc,
"Using the generic type `{0}' " +
"requires {1} type arguments",
TypeManager.CSharpName (t),
}
}
- return Error_MemberLookupFailed (queried_type, lookup);
+ return Error_MemberLookupFailed (ec, queried_type, lookup);
}
- protected virtual Expression Error_MemberLookupFailed (Type type, MemberInfo[] members)
+ protected virtual Expression Error_MemberLookupFailed (ResolveContext ec, Type type, MemberInfo[] members)
{
for (int i = 0; i < members.Length; ++i) {
if (!(members [i] is MethodBase))
return new MethodGroupExpr (members, type, loc, true);
}
- protected virtual void Error_NegativeArrayIndex (Location loc)
+ protected virtual void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
{
throw new NotImplementedException ();
}
- protected void Error_PointerInsideExpressionTree ()
+ protected void Error_PointerInsideExpressionTree (ResolveContext ec)
{
- Report.Error (1944, loc, "An expression tree cannot contain an unsafe pointer operation");
+ ec.Report.Error (1944, loc, "An expression tree cannot contain an unsafe pointer operation");
}
/// <summary>
{
MethodGroupExpr operator_group;
string mname = Operator.GetMetadataName (is_true ? Operator.OpType.True : Operator.OpType.False);
- operator_group = MethodLookup (ec.CurrentType, e.Type, mname, loc) as MethodGroupExpr;
+ operator_group = MethodLookup (ec.Compiler, ec.CurrentType, e.Type, mname, loc) as MethodGroupExpr;
if (operator_group == null)
return null;
/// <summary>
/// Reports that we were expecting `expr' to be of class `expected'
/// </summary>
- public void Error_UnexpectedKind (MemberCore mc, string expected, Location loc)
+ public void Error_UnexpectedKind (Report r, MemberCore mc, string expected, Location loc)
{
- Error_UnexpectedKind (mc, expected, ExprClassName, loc);
+ Error_UnexpectedKind (r, mc, expected, ExprClassName, loc);
}
- public void Error_UnexpectedKind (MemberCore mc, string expected, string was, Location loc)
+ public void Error_UnexpectedKind (Report r, MemberCore mc, string expected, string was, Location loc)
{
string name;
if (mc != null)
else
name = GetSignatureForError ();
- Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
+ r.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
name, was, expected);
}
- public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
+ public void Error_UnexpectedKind (ResolveContext ec, ResolveFlags flags, Location loc)
{
string [] valid = new string [4];
int count = 0;
sb.Append (valid [count - 1]);
}
- Report.Error (119, loc,
+ ec.Report.Error (119, loc,
"Expression denotes a `{0}', where a `{1}' was expected", ExprClassName, sb.ToString ());
}
- public static void UnsafeError (Location loc)
+ public static void UnsafeError (ResolveContext ec, Location loc)
+ {
+ UnsafeError (ec.Report, loc);
+ }
+
+ public static void UnsafeError (Report Report, Location loc)
{
Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
}
return 0;
}
- protected void Error_CannotCallAbstractBase (string name)
+ protected void Error_CannotCallAbstractBase (ResolveContext ec, string name)
{
- Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
+ ec.Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
}
protected void Error_CannotModifyIntermediateExpressionValue (ResolveContext ec)
{
- Report.SymbolRelatedToPreviousError (type);
+ ec.Report.SymbolRelatedToPreviousError (type);
if (ec.CurrentInitializerVariable != null) {
- Report.Error (1918, loc, "Members of value type `{0}' cannot be assigned using a property `{1}' object initializer",
+ ec.Report.Error (1918, loc, "Members of value type `{0}' cannot be assigned using a property `{1}' object initializer",
TypeManager.CSharpName (type), GetSignatureForError ());
} else {
- Report.Error (1612, loc, "Cannot modify a value type return value of `{0}'. Consider storing the value in a temporary variable",
+ ec.Report.Error (1612, loc, "Cannot modify a value type return value of `{0}'. Consider storing the value in a temporary variable",
GetSignatureForError ());
}
}
- public void Error_ExpressionCannotBeGeneric (Location loc)
- {
- Report.Error (307, loc, "The {0} `{1}' cannot be used with type arguments",
- ExprClassName, GetSignatureForError ());
- }
-
//
// Converts `source' to an int, uint, long or ulong.
//
Constant c = converted as Constant;
if (c != null) {
if (c.IsNegative) {
- Error_NegativeArrayIndex (source.loc);
+ Error_NegativeArrayIndex (ec, source.loc);
}
return c;
}
//
public abstract Expression CreateExpressionTree (ResolveContext ec);
- protected Expression CreateExpressionFactoryCall (string name, Arguments args)
+ protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, Arguments args)
{
- return CreateExpressionFactoryCall (name, null, args, loc);
+ return CreateExpressionFactoryCall (ec, name, null, args, loc);
}
- protected Expression CreateExpressionFactoryCall (string name, TypeArguments typeArguments, Arguments args)
+ protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args)
{
- return CreateExpressionFactoryCall (name, typeArguments, args, loc);
+ return CreateExpressionFactoryCall (ec, name, typeArguments, args, loc);
}
- public static Expression CreateExpressionFactoryCall (string name, TypeArguments typeArguments, Arguments args, Location loc)
+ public static Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args, Location loc)
{
- return new Invocation (new MemberAccess (CreateExpressionTypeExpression (loc), name, typeArguments, loc), args);
+ return new Invocation (new MemberAccess (CreateExpressionTypeExpression (ec, loc), name, typeArguments, loc), args);
}
- protected static TypeExpr CreateExpressionTypeExpression (Location loc)
+ protected static TypeExpr CreateExpressionTypeExpression (ResolveContext ec, Location loc)
{
TypeExpr texpr = TypeManager.expression_type_expr;
if (texpr == null) {
- Type t = TypeManager.CoreLookupType ("System.Linq.Expressions", "Expression", Kind.Class, true);
+ Type t = TypeManager.CoreLookupType (ec.Compiler, "System.Linq.Expressions", "Expression", Kind.Class, true);
if (t == null)
return null;
ExpressionStatement es = e as ExpressionStatement;
if (es == null)
- Error_InvalidExpressionStatement ();
+ Error_InvalidExpressionStatement (ec);
return es;
}
args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
if (type.IsPointer || child.Type.IsPointer)
- Error_PointerInsideExpressionTree ();
+ Error_PointerInsideExpressionTree (ec);
- return CreateExpressionFactoryCall (ec.HasSet (ResolveContext.Options.CheckedScope) ? "ConvertChecked" : "Convert", args);
+ return CreateExpressionFactoryCall (ec, ec.HasSet (ResolveContext.Options.CheckedScope) ? "ConvertChecked" : "Convert", args);
}
public override Expression DoResolve (ResolveContext ec)
new TypeOf (new TypeExpression (type, loc), loc));
if (type.IsPointer)
- Error_PointerInsideExpressionTree ();
+ Error_PointerInsideExpressionTree (ec);
- return CreateExpressionFactoryCall ("Convert", args);
+ return CreateExpressionFactoryCall (ec, "Convert", args);
}
public override Constant Increment ()
public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
{
if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
- Report.Error (445, loc, "Cannot modify the result of an unboxing conversion");
+ ec.Report.Error (445, loc, "Cannot modify the result of an unboxing conversion");
return base.DoResolveLValue (ec, right_side);
}
// Even if resolved result is a constant original expression was not
// and attribute accepts constants only
//
- Attribute.Error_AttributeArgumentNotValid (orig_expr.Location);
+ Attribute.Error_AttributeArgumentNotValid (ec, orig_expr.Location);
value = null;
return false;
}
public static void Error_ObjectRefRequired (ResolveContext ec, Location l, string name)
{
if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
- Report.Error (236, l,
+ ec.Report.Error (236, l,
"A field initializer cannot reference the nonstatic field, method, or property `{0}'",
name);
else
- Report.Error (120, l,
+ ec.Report.Error (120, l,
"An object reference is required to access non-static member `{0}'",
name);
}
public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
{
- int errors = Report.Errors;
+ int errors = ec.Compiler.Report.Errors;
FullNamedExpression fne = ec.LookupNamespaceOrType (Name, loc, /*ignore_cs0104=*/ false);
if (fne != null) {
if (!HasTypeArguments && Name == "dynamic" && RootContext.Version > LanguageVersion.V_3)
return new DynamicTypeExpr (loc);
- if (silent || errors != Report.Errors)
+ if (silent || errors != ec.Compiler.Report.Errors)
return null;
Error_TypeOrNamespaceNotFound (ec);
if (ec.CurrentTypeDefinition != null) {
MemberCore mc = ec.CurrentTypeDefinition.GetDefinition (Name);
if (mc != null) {
- Error_UnexpectedKind (mc, "type", GetMemberType (mc), loc);
+ Error_UnexpectedKind (ec.Compiler.Report, mc, "type", GetMemberType (mc), loc);
return;
}
}
foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
Type type = a.GetType (fullname);
if (type != null) {
- Report.SymbolRelatedToPreviousError (type);
- Expression.ErrorIsInaccesible (loc, TypeManager.CSharpName (type));
+ ec.Compiler.Report.SymbolRelatedToPreviousError (type);
+ Expression.ErrorIsInaccesible (loc, TypeManager.CSharpName (type), ec.Compiler.Report);
return;
}
}
}
}
- NamespaceEntry.Error_NamespaceNotFound (loc, Name);
+ NamespaceEntry.Error_NamespaceNotFound (loc, Name, ec.Compiler.Report);
}
// TODO: I am still not convinced about this. If someone else will need it
Type almost_matched_type = null;
ArrayList almost_matched = null;
for (Type lookup_ds = ec.CurrentType; lookup_ds != null; lookup_ds = lookup_ds.DeclaringType) {
- e = MemberLookup (ec.CurrentType, lookup_ds, Name, loc);
+ e = MemberLookup (ec.Compiler, ec.CurrentType, lookup_ds, Name, loc);
if (e != null) {
PropertyExpr pe = e as PropertyExpr;
if (pe != null) {
if (li != null)
li.Used = true;
- Error_VariableIsUsedBeforeItIsDeclared (Name);
+ Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
return null;
}
}
almost_matched_type = ec.CurrentType;
string type_name = ec.MemberContext.CurrentType == null ? null : ec.MemberContext.CurrentType.Name;
- return Error_MemberLookupFailed (ec.CurrentType, null, almost_matched_type, Name,
+ return Error_MemberLookupFailed (ec, ec.CurrentType, null, almost_matched_type, Name,
type_name, AllMemberTypes, AllBindingFlags);
}
if (!targs.Resolve (ec))
return null;
- me.SetTypeArguments (targs);
+ me.SetTypeArguments (ec, targs);
}
if (!me.IsStatic && (me.InstanceExpression != null && me.InstanceExpression != EmptyExpression.Null) &&
me.InstanceExpression.Type != me.DeclaringType &&
!TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
(!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
- Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
+ ec.Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
return null;
}
//
if (type == null) {
Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, false);
- FullNamedExpression fne = ns.Lookup (name, loc);
+ FullNamedExpression fne = ns.Lookup (ec.Compiler, name, loc);
if (fne != null)
type = fne.Type;
}
/// </summary>
public Expression InstanceExpression;
- public static void error176 (Location loc, string name)
+ public static void error176 (ResolveContext ec, Location loc, string name)
{
- Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
+ ec.Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
"with an instance reference, qualify it with a type name instead", name);
}
- public static void Error_BaseAccessInExpressionTree (Location loc)
+ public static void Error_BaseAccessInExpressionTree (ResolveContext ec, Location loc)
{
- Report.Error (831, loc, "An expression tree may not contain a base access");
+ ec.Report.Error (831, loc, "An expression tree may not contain a base access");
}
public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
// always do all necessary checks
ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (left.Type);
if (oa != null && !ec.IsObsolete) {
- AttributeTester.Report_ObsoleteMessage (oa, left.GetSignatureForError (), loc);
+ AttributeTester.Report_ObsoleteMessage (oa, left.GetSignatureForError (), loc, ec.Report);
}
GenericTypeExpr ct = left as GenericTypeExpr;
if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
return this;
- return ResolveExtensionMemberAccess (left);
+ return ResolveExtensionMemberAccess (ec, left);
}
InstanceExpression = left;
return this;
}
- protected virtual MemberExpr ResolveExtensionMemberAccess (Expression left)
+ protected virtual MemberExpr ResolveExtensionMemberAccess (ResolveContext ec, Expression left)
{
- error176 (loc, GetSignatureForError ());
+ error176 (ec, loc, GetSignatureForError ());
return this;
}
ec.ig.Emit (OpCodes.Dup);
}
- public virtual void SetTypeArguments (TypeArguments ta)
+ public virtual void SetTypeArguments (ResolveContext ec, TypeArguments ta)
{
// TODO: need to get correct member type
- Report.Error (307, loc, "The property `{0}' cannot be used with type arguments",
+ ec.Report.Error (307, loc, "The property `{0}' cannot be used with type arguments",
GetSignatureForError ());
}
}
return base.OverloadResolve (ec, ref arguments, false, loc);
e.ExtensionExpression = ExtensionExpression;
- e.SetTypeArguments (type_arguments);
+ e.SetTypeArguments (ec, type_arguments);
return e.ResolveOverloadExtensions (ec, ref arguments, e.namespace_entry, loc);
}
}
{
public interface IErrorHandler
{
- bool AmbiguousCall (MethodBase ambiguous);
+ bool AmbiguousCall (ResolveContext ec, MethodBase ambiguous);
bool NoExactMatch (ResolveContext ec, MethodBase method);
}
q = TypeManager.GetTypeArguments (q) [0];
}
- p = Delegate.GetInvokeMethod (null, p).ReturnType;
- q = Delegate.GetInvokeMethod (null, q).ReturnType;
+ p = Delegate.GetInvokeMethod (ec.Compiler, null, p).ReturnType;
+ q = Delegate.GetInvokeMethod (ec.Compiler, null, q).ReturnType;
if (p == TypeManager.void_type && q != TypeManager.void_type)
return 2;
if (q == TypeManager.void_type && p != TypeManager.void_type)
return false;
}
- protected override MemberExpr ResolveExtensionMemberAccess (Expression left)
+ protected override MemberExpr ResolveExtensionMemberAccess (ResolveContext ec, Expression left)
{
if (!IsStatic)
- return base.ResolveExtensionMemberAccess (left);
+ return base.ResolveExtensionMemberAccess (ec, left);
//
// When left side is an expression and at least one candidate method is
public override Expression CreateExpressionTree (ResolveContext ec)
{
if (best_candidate == null) {
- Report.Error (1953, loc, "An expression tree cannot contain an expression with method group");
+ ec.Report.Error (1953, loc, "An expression tree cannot contain an expression with method group");
return null;
}
IMethodData md = TypeManager.GetMethod (best_candidate);
if (md != null && md.IsExcluded ())
- Report.Error (765, loc,
+ ec.Report.Error (765, loc,
"Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
return new TypeOfMethod (best_candidate, loc);
return this;
}
- public void ReportUsageError ()
+ public void ReportUsageError (ResolveContext ec)
{
- Report.Error (654, loc, "Method `" + DeclaringType + "." +
+ ec.Report.Error (654, loc, "Method `" + DeclaringType + "." +
Name + "()' is referenced without parentheses");
}
override public void Emit (EmitContext ec)
{
- ReportUsageError ();
+ throw new NotSupportedException ();
+ // ReportUsageError ();
}
public void EmitCall (EmitContext ec, Arguments arguments)
Invocation.EmitCall (ec, IsBase, InstanceExpression, best_candidate, arguments, loc);
}
- void Error_AmbiguousCall (MethodBase ambiguous)
+ void Error_AmbiguousCall (ResolveContext ec, MethodBase ambiguous)
{
- if (CustomErrorHandler != null && CustomErrorHandler.AmbiguousCall (ambiguous))
+ if (CustomErrorHandler != null && CustomErrorHandler.AmbiguousCall (ec, ambiguous))
return;
- Report.SymbolRelatedToPreviousError (best_candidate);
- Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
+ ec.Report.SymbolRelatedToPreviousError (best_candidate);
+ ec.Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (best_candidate));
}
ExtensionMethodGroupExpr emg = this as ExtensionMethodGroupExpr;
if (a is CollectionElementInitializer.ElementInitializerArgument) {
- Report.SymbolRelatedToPreviousError (method);
+ ec.Report.SymbolRelatedToPreviousError (method);
if ((expected_par.FixedParameters [idx].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
- Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have 'ref', or `out' modifier",
+ ec.Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have 'ref', or `out' modifier",
TypeManager.CSharpSignature (method));
return;
}
- Report.Error (1950, loc, "The best overloaded collection initalizer method `{0}' has some invalid arguments",
+ ec.Report.Error (1950, loc, "The best overloaded collection initalizer method `{0}' has some invalid arguments",
TypeManager.CSharpSignature (method));
} else if (TypeManager.IsDelegateType (method.DeclaringType)) {
- Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
+ ec.Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
TypeManager.CSharpName (method.DeclaringType));
} else {
- Report.SymbolRelatedToPreviousError (method);
+ ec.Report.SymbolRelatedToPreviousError (method);
if (emg != null) {
- Report.Error (1928, loc,
+ ec.Report.Error (1928, loc,
"Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments",
emg.ExtensionExpression.GetSignatureForError (),
emg.Name, TypeManager.CSharpSignature (method));
} else {
- Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
+ ec.Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
TypeManager.CSharpSignature (method));
}
}
if (((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) ^
(a.Modifier & (Parameter.Modifier.REF | Parameter.Modifier.OUT))) != 0) {
if ((mod & Parameter.Modifier.ISBYREF) == 0)
- Report.Error (1615, loc, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier",
+ ec.Report.Error (1615, loc, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier",
index, Parameter.GetModifierSignature (a.Modifier));
else
- Report.Error (1620, loc, "Argument `#{0}' is missing `{1}' modifier",
+ ec.Report.Error (1620, loc, "Argument `#{0}' is missing `{1}' modifier",
index, Parameter.GetModifierSignature (mod));
} else {
string p1 = a.GetSignatureForError ();
string p2 = TypeManager.CSharpName (paramType);
if (p1 == p2) {
- Report.ExtraInformation (loc, "(equally named types possibly from different assemblies in previous ");
- Report.SymbolRelatedToPreviousError (a.Expr.Type);
- Report.SymbolRelatedToPreviousError (paramType);
+ ec.Report.ExtraInformation (loc, "(equally named types possibly from different assemblies in previous ");
+ ec.Report.SymbolRelatedToPreviousError (a.Expr.Type);
+ ec.Report.SymbolRelatedToPreviousError (paramType);
}
if (idx == 0 && emg != null) {
- Report.Error (1929, loc,
+ ec.Report.Error (1929, loc,
"Extension method instance type `{0}' cannot be converted to `{1}'", p1, p2);
} else {
- Report.Error (1503, loc,
+ ec.Report.Error (1503, loc,
"Argument `#{0}' cannot convert `{1}' expression to type `{2}'", index, p1, p2);
}
}
public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type target, bool expl)
{
- Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
+ ec.Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
Name, TypeManager.CSharpName (target));
}
- void Error_ArgumentCountWrong (int arg_count)
+ void Error_ArgumentCountWrong (ResolveContext ec, int arg_count)
{
- Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
+ ec.Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
Name, arg_count.ToString ());
}
if (RootContext.Version == LanguageVersion.ISO_1 && Name == "Invoke" && TypeManager.IsDelegateType (DeclaringType)) {
if (!may_fail)
- Report.Error (1533, loc, "Invoke cannot be called directly on a delegate");
+ ec.Report.Error (1533, loc, "Invoke cannot be called directly on a delegate");
return null;
}
//
// Enable message recording, it's used mainly by lambda expressions
//
- Report.IMessageRecorder msg_recorder = new Report.MessageRecorder ();
- Report.IMessageRecorder prev_recorder = Report.SetMessageRecorder (msg_recorder);
+ SessionReportPrinter msg_recorder = new SessionReportPrinter ();
+ ReportPrinter prev_recorder = ec.Report.SetPrinter (msg_recorder);
//
// First we construct the set of applicable methods
}
}
- Report.SetMessageRecorder (prev_recorder);
+ ec.Report.SetPrinter (prev_recorder);
if (msg_recorder != null && !msg_recorder.IsEmpty) {
if (!may_fail)
- msg_recorder.PrintMessages ();
+ msg_recorder.Merge (prev_recorder);
return null;
}
ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (type, Name, loc);
if (ex_method_lookup != null) {
ex_method_lookup.ExtensionExpression = InstanceExpression;
- ex_method_lookup.SetTypeArguments (type_arguments);
+ ex_method_lookup.SetTypeArguments (ec, type_arguments);
return ex_method_lookup.OverloadResolve (ec, ref Arguments, may_fail, loc);
}
}
if (arg_count == pd.Count || pd.HasParams) {
if (TypeManager.IsGenericMethodDefinition (best_candidate)) {
if (type_arguments == null) {
- Report.Error (411, loc,
+ ec.Report.Error (411, loc,
"The type arguments for method `{0}' cannot be inferred from " +
"the usage. Try specifying the type arguments explicitly",
TypeManager.CSharpSignature (best_candidate));
Type[] g_args = TypeManager.GetGenericArguments (best_candidate);
if (type_arguments.Count != g_args.Length) {
- Report.SymbolRelatedToPreviousError (best_candidate);
- Report.Error (305, loc, "Using the generic method `{0}' requires `{1}' type argument(s)",
+ ec.Report.SymbolRelatedToPreviousError (best_candidate);
+ ec.Report.Error (305, loc, "Using the generic method `{0}' requires `{1}' type argument(s)",
TypeManager.CSharpSignature (best_candidate),
g_args.Length.ToString ());
return null;
// base class (CS1540). If the qualifier_type is a base of the
// ec.CurrentType and the lookup succeeds with the latter one,
// then we are in this situation.
- Error_CannotAccessProtected (loc, best_candidate, queried_type, ec.CurrentType);
+ Error_CannotAccessProtected (ec, loc, best_candidate, queried_type, ec.CurrentType);
} else {
- Report.SymbolRelatedToPreviousError (best_candidate);
- ErrorIsInaccesible (loc, GetSignatureForError ());
+ ec.Report.SymbolRelatedToPreviousError (best_candidate);
+ ErrorIsInaccesible (loc, GetSignatureForError (), ec.Report);
}
}
// We failed to find any method with correct argument count
//
if (Name == ConstructorInfo.ConstructorName) {
- Report.SymbolRelatedToPreviousError (queried_type);
- Report.Error (1729, loc,
+ ec.Report.SymbolRelatedToPreviousError (queried_type);
+ ec.Report.Error (1729, loc,
"The type `{0}' does not contain a constructor that takes `{1}' arguments",
TypeManager.CSharpName (queried_type), arg_count);
} else {
- Error_ArgumentCountWrong (arg_count);
+ Error_ArgumentCountWrong (ec, arg_count);
}
return null;
candidate, cand_params))
{
if (!may_fail)
- Report.SymbolRelatedToPreviousError (candidate);
+ ec.Report.SymbolRelatedToPreviousError (candidate);
ambiguous = candidate;
}
}
if (ambiguous != null) {
- Error_AmbiguousCall (ambiguous);
+ Error_AmbiguousCall (ec, ambiguous);
return this;
}
//
ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (the_method);
if (oa != null && !ec.IsObsolete)
- AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
+ AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
IMethodData data = TypeManager.GetMethod (the_method);
if (data != null)
return this;
}
- public override void SetTypeArguments (TypeArguments ta)
+ public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
{
type_arguments = ta;
}
AParametersCollection pd = TypeManager.GetParameterData (method);
int param_count = GetApplicableParametersCount (method, pd);
- int errors = Report.Errors;
+ int errors = ec.Report.Errors;
Parameter.Modifier p_mod = 0;
Type pt = null;
int a_idx = 0, a_pos = 0;
int name_index = pd.GetParameterIndexByName (na.Name.Value);
if (name_index < 0 || name_index >= param_count) {
if (DeclaringType != null && TypeManager.IsDelegateType (DeclaringType)) {
- Report.SymbolRelatedToPreviousError (DeclaringType);
- Report.Error (1746, na.Name.Location,
+ ec.Report.SymbolRelatedToPreviousError (DeclaringType);
+ ec.Report.Error (1746, na.Name.Location,
"The delegate `{0}' does not contain a parameter named `{1}'",
TypeManager.CSharpName (DeclaringType), na.Name.Value);
} else {
- Report.SymbolRelatedToPreviousError (best_candidate);
- Report.Error (1739, na.Name.Location,
+ ec.Report.SymbolRelatedToPreviousError (best_candidate);
+ ec.Report.Error (1739, na.Name.Location,
"The best overloaded method match for `{0}' does not contain a parameter named `{1}'",
TypeManager.CSharpSignature (method), na.Name.Value);
}
} else if (arguments[name_index] != a) {
if (DeclaringType != null && TypeManager.IsDelegateType (DeclaringType))
- Report.SymbolRelatedToPreviousError (DeclaringType);
+ ec.Report.SymbolRelatedToPreviousError (DeclaringType);
else
- Report.SymbolRelatedToPreviousError (best_candidate);
+ ec.Report.SymbolRelatedToPreviousError (best_candidate);
- Report.Error (1744, na.Name.Location,
+ ec.Report.Error (1744, na.Name.Location,
"Named argument `{0}' cannot be used for a parameter which has positional argument specified",
na.Name.Value);
}
}
if (a_idx != arg_count) {
- if (!may_fail && Report.Errors == errors) {
+ if (!may_fail && ec.Report.Errors == errors) {
if (CustomErrorHandler != null)
CustomErrorHandler.NoExactMatch (ec, best_candidate);
else
if (arg_count < param_count) {
if (!may_fail)
- Error_ArgumentCountWrong (arg_count);
+ Error_ArgumentCountWrong (ec, arg_count);
return false;
}
if (has_unsafe_arg && !ec.IsUnsafe) {
if (!may_fail)
- UnsafeError (loc);
+ UnsafeError (ec, loc);
return false;
}
Type t = fi.FieldType;
if (t.IsPointer && !ec.IsUnsafe) {
- UnsafeError (loc);
+ UnsafeError (ec, loc);
}
return base.ResolveMemberAccess (ec, left, loc, original);
instance,
CreateTypeOfExpression ());
- return CreateExpressionFactoryCall ("Field", args);
+ return CreateExpressionFactoryCall (ec, "Field", args);
}
public Expression CreateTypeOfExpression ()
} else {
ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
if (oa != null)
- AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
+ AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc, ec.Report);
}
}
if (fb != null) {
IFixedExpression fe = InstanceExpression as IFixedExpression;
if (!ec.HasSet (ResolveContext.Options.FixedInitializerScope) && (fe == null || !fe.IsFixed)) {
- Report.Error (1666, loc, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
+ ec.Report.Error (1666, loc, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
}
if (InstanceExpression.eclass != ExprClass.Variable) {
- Report.SymbolRelatedToPreviousError (FieldInfo);
- Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields",
+ ec.Report.SymbolRelatedToPreviousError (FieldInfo);
+ ec.Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields",
TypeManager.GetFullNameSignature (FieldInfo));
} else if (var != null && var.IsHoisted) {
- AnonymousMethodExpression.Error_AddressOfCapturedVar (var, loc);
+ AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, var, loc);
}
return new FixedBufferPtr (this, fb.ElementType, loc).Resolve (ec);
};
// The return value is always null. Returning a value simplifies calling code.
- Expression Report_AssignToReadonly (Expression right_side)
+ Expression Report_AssignToReadonly (ResolveContext ec, Expression right_side)
{
int i = 0;
if (right_side == EmptyExpression.OutAccess || right_side == EmptyExpression.LValueMemberOutAccess)
i += 2;
if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
i += 4;
- Report.Error (codes [i], loc, msgs [i], GetSignatureForError ());
+ ec.Report.Error (codes [i], loc, msgs [i], GetSignatureForError ());
return null;
}
if ((right_side == EmptyExpression.UnaryAddress || right_side == EmptyExpression.OutAccess) &&
(fb.ModFlags & Modifiers.VOLATILE) != 0) {
- Report.Warning (420, 1, loc,
+ ec.Report.Warning (420, 1, loc,
"`{0}': A volatile field references will not be treated as volatile",
fb.GetSignatureForError ());
}
if (FieldInfo.IsInitOnly) {
// InitOnly fields can only be assigned in constructors or initializers
if (!ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.ConstructorScope))
- return Report_AssignToReadonly (right_side);
+ return Report_AssignToReadonly (ec, right_side);
if (ec.HasSet (ResolveContext.Options.ConstructorScope)) {
Type ctype = ec.CurrentType;
// InitOnly fields cannot be assigned-to in a different constructor from their declaring type
if (!TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
- return Report_AssignToReadonly (right_side);
+ return Report_AssignToReadonly (ec, right_side);
// static InitOnly fields cannot be assigned-to in an instance constructor
if (IsStatic && !ec.IsStatic)
- return Report_AssignToReadonly (right_side);
+ return Report_AssignToReadonly (ec, right_side);
// instance constructors can't modify InitOnly fields of other instances of the same type
if (!IsStatic && !(InstanceExpression is This))
- return Report_AssignToReadonly (right_side);
+ return Report_AssignToReadonly (ec, right_side);
}
}
if (right_side == EmptyExpression.OutAccess &&
!IsStatic && !(InstanceExpression is This) && TypeManager.mbr_type != null && TypeManager.IsSubclassOf (DeclaringType, TypeManager.mbr_type)) {
- Report.SymbolRelatedToPreviousError (DeclaringType);
- Report.Warning (197, 1, loc,
+ ec.Report.SymbolRelatedToPreviousError (DeclaringType);
+ ec.Report.Warning (197, 1, loc,
"Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
GetSignatureForError ());
}
public override void CheckMarshalByRefAccess (ResolveContext ec)
{
if (is_marshal_by_ref () && !(InstanceExpression is This)) {
- Report.SymbolRelatedToPreviousError (DeclaringType);
- Report.Warning (1690, 1, loc, "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
+ ec.Report.SymbolRelatedToPreviousError (DeclaringType);
+ ec.Report.Warning (1690, 1, loc, "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
GetSignatureForError ());
}
}
base.EmitSideEffect (ec);
}
- public override void Error_VariableIsUsedBeforeItIsDeclared (string name)
+ public override void Error_VariableIsUsedBeforeItIsDeclared (Report r, string name)
{
- Report.Error (844, loc,
+ r.Error (844, loc,
"A local variable `{0}' cannot be used before it is declared. Consider renaming the local variable when it hides the field `{1}'",
name, GetSignatureForError ());
}
if (IsSingleDimensionalArrayLength ()) {
args = new Arguments (1);
args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
- return CreateExpressionFactoryCall ("ArrayLength", args);
+ return CreateExpressionFactoryCall (ec, "ArrayLength", args);
}
if (is_base) {
- Error_BaseAccessInExpressionTree (loc);
+ Error_BaseAccessInExpressionTree (ec, loc);
return null;
}
else
args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
args.Add (new Argument (new TypeOfMethod (getter, loc)));
- return CreateExpressionFactoryCall ("Property", args);
+ return CreateExpressionFactoryCall (ec, "Property", args);
}
public Expression CreateSetterTypeOfExpression ()
!TypeManager.IsInstantiationOfSameGenericType (InstanceExpression.Type, ec.CurrentType) &&
!TypeManager.IsNestedChildOf (ec.CurrentType, InstanceExpression.Type) &&
!TypeManager.IsSubclassOf (InstanceExpression.Type, ec.CurrentType)) {
- Report.SymbolRelatedToPreviousError (PropertyInfo);
- Error_CannotAccessProtected (loc, PropertyInfo, InstanceExpression.Type, ec.CurrentType);
+ ec.Report.SymbolRelatedToPreviousError (PropertyInfo);
+ Error_CannotAccessProtected (ec, loc, PropertyInfo, InstanceExpression.Type, ec.CurrentType);
return false;
}
return true;
}
- void Error_PropertyNotFound (MethodInfo mi, bool getter)
+ void Error_PropertyNotFound (ResolveContext ec, MethodInfo mi, bool getter)
{
// TODO: correctly we should compare arguments but it will lead to bigger changes
if (mi is MethodBuilder) {
- Error_TypeDoesNotContainDefinition (loc, PropertyInfo.DeclaringType, Name);
+ Error_TypeDoesNotContainDefinition (ec, loc, PropertyInfo.DeclaringType, Name);
return;
}
sig.Append (Name);
sig.Append (iparams.GetSignatureForError ());
- Report.SymbolRelatedToPreviousError (mi);
- Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
+ ec.Report.SymbolRelatedToPreviousError (mi);
+ ec.Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
Name, sig.ToString ());
}
if (getter != null){
if (TypeManager.GetParameterData (getter).Count != 0){
- Error_PropertyNotFound (getter, true);
+ Error_PropertyNotFound (ec, getter, true);
return null;
}
}
return null;
if (InstanceExpression != EmptyExpression.Null) {
- Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
+ ec.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
TypeManager.GetFullNameSignature (PropertyInfo));
return null;
}
!IsAccessorAccessible (ec.CurrentType, getter, out must_do_cs1540_check)) {
PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
if (pm != null && pm.HasCustomAccessModifier) {
- Report.SymbolRelatedToPreviousError (pm);
- Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
+ ec.Report.SymbolRelatedToPreviousError (pm);
+ ec.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
TypeManager.CSharpSignature (getter));
}
else {
- Report.SymbolRelatedToPreviousError (getter);
- ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
+ ec.Report.SymbolRelatedToPreviousError (getter);
+ ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter), ec.Report);
}
return null;
}
// Only base will allow this invocation to happen.
//
if (IsBase && getter.IsAbstract) {
- Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
+ Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (PropertyInfo));
}
if (PropertyInfo.PropertyType.IsPointer && !ec.IsUnsafe){
- UnsafeError (loc);
+ UnsafeError (ec, loc);
}
if (!ec.IsObsolete) {
} else {
ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (PropertyInfo);
if (oa != null)
- AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
+ AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
}
}
{
if (right_side == EmptyExpression.OutAccess) {
if (ec.CurrentBlock.Toplevel.GetParameterReference (PropertyInfo.Name, loc) is MemberAccess) {
- Report.Error (1939, loc, "A range variable `{0}' may not be passes as `ref' or `out' parameter",
+ ec.Report.Error (1939, loc, "A range variable `{0}' may not be passes as `ref' or `out' parameter",
PropertyInfo.Name);
} else {
- Report.Error (206, loc, "A property or indexer `{0}' may not be passed as `ref' or `out' parameter",
+ ec.Report.Error (206, loc, "A property or indexer `{0}' may not be passed as `ref' or `out' parameter",
GetSignatureForError ());
}
return null;
return null;
if (ec.CurrentBlock.Toplevel.GetParameterReference (PropertyInfo.Name, loc) is MemberAccess) {
- Report.Error (1947, loc, "A range variable `{0}' cannot be assigned to. Consider using `let' clause to store the value",
+ ec.Report.Error (1947, loc, "A range variable `{0}' cannot be assigned to. Consider using `let' clause to store the value",
PropertyInfo.Name);
} else {
- Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read only)",
+ ec.Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read only)",
GetSignatureForError ());
}
return null;
}
if (TypeManager.GetParameterData (setter).Count != 1){
- Error_PropertyNotFound (setter, false);
+ Error_PropertyNotFound (ec, setter, false);
return null;
}
if (!IsAccessorAccessible (ec.CurrentType, setter, out must_do_cs1540_check)) {
PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
if (pm != null && pm.HasCustomAccessModifier) {
- Report.SymbolRelatedToPreviousError (pm);
- Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
+ ec.Report.SymbolRelatedToPreviousError (pm);
+ ec.Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
TypeManager.CSharpSignature (setter));
}
else {
- Report.SymbolRelatedToPreviousError (setter);
- ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
+ ec.Report.SymbolRelatedToPreviousError (setter);
+ ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter), ec.Report);
}
return null;
}
// Only base will allow this invocation to happen.
//
if (IsBase && setter.IsAbstract){
- Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
+ Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (PropertyInfo));
}
if (PropertyInfo.PropertyType.IsPointer && !ec.IsUnsafe) {
- UnsafeError (loc);
+ UnsafeError (ec, loc);
}
if (!ec.IsObsolete) {
} else {
ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (PropertyInfo);
if (oa != null)
- AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
+ AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
}
}
}
}
- public void Error_AssignmentEventOnly ()
+ public void Error_AssignmentEventOnly (ResolveContext ec)
{
- Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of `+=' or `-=' operator",
+ ec.Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of `+=' or `-=' operator",
GetSignatureForError ());
}
mi.CheckObsoleteness (loc);
if ((mi.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0 && !ec.HasSet (ResolveContext.Options.CompoundAssignmentScope))
- Error_AssignmentEventOnly ();
+ Error_AssignmentEventOnly (ec);
FieldExpr ml = new FieldExpr (mi.BackingField.FieldBuilder, loc);
}
if (left is This && !ec.HasSet (ResolveContext.Options.CompoundAssignmentScope))
- Error_AssignmentEventOnly ();
+ Error_AssignmentEventOnly (ec);
return base.ResolveMemberAccess (ec, left, loc, original);
}
return false;
if (IsBase && add_accessor.IsAbstract) {
- Error_CannotCallAbstractBase(TypeManager.CSharpSignature(add_accessor));
+ Error_CannotCallAbstractBase (ec, TypeManager.CSharpSignature(add_accessor));
return false;
}
!TypeManager.IsInstantiationOfSameGenericType (InstanceExpression.Type, ec.CurrentType) &&
!TypeManager.IsNestedChildOf (ec.CurrentType, InstanceExpression.Type) &&
!TypeManager.IsSubclassOf (InstanceExpression.Type, ec.CurrentType)) {
- Report.SymbolRelatedToPreviousError (EventInfo);
- ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
+ ec.Report.SymbolRelatedToPreviousError (EventInfo);
+ ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo), ec.Report);
return false;
}
public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
{
// contexts where an LValue is valid have already devolved to FieldExprs
- Error_CannotAssign ();
+ Error_CannotAssign (ec);
return null;
}
bool must_do_cs1540_check;
if (!(IsAccessorAccessible (ec.CurrentType, add_accessor, out must_do_cs1540_check) &&
IsAccessorAccessible (ec.CurrentType, remove_accessor, out must_do_cs1540_check))) {
- Report.SymbolRelatedToPreviousError (EventInfo);
- ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
+ ec.Report.SymbolRelatedToPreviousError (EventInfo);
+ ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo), ec.Report);
return null;
}
return null;
if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
- Error_CannotAssign ();
+ Error_CannotAssign (ec);
return null;
}
} else {
ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (EventInfo);
if (oa != null)
- AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
+ AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
}
}
public override void Emit (EmitContext ec)
{
- Error_CannotAssign ();
+ throw new NotSupportedException ();
+ //Error_CannotAssign ();
}
- public void Error_CannotAssign ()
+ public void Error_CannotAssign (ResolveContext ec)
{
- Report.Error (70, loc,
+ ec.Report.Error (70, loc,
"The event `{0}' can only appear on the left hand side of += or -= when used outside of the type `{1}'",
GetSignatureForError (), TypeManager.CSharpName (EventInfo.DeclaringType));
}
type = right_side.Type;
if (type == TypeManager.null_type || type == TypeManager.void_type || type == InternalType.AnonymousMethod) {
- Report.Error (815, loc, "An implicitly typed local variable declaration cannot be initialized with `{0}'",
+ ec.Report.Error (815, loc, "An implicitly typed local variable declaration cannot be initialized with `{0}'",
right_side.GetSignatureForError ());
return false;
}
if (RootContext.Version < LanguageVersion.V_3)
base.Error_TypeOrNamespaceNotFound (ec);
else
- Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
+ ec.Compiler.Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
}
public override TypeExpr ResolveAsContextualType (IMemberContext rc, bool silent)
return te;
if (RootContext.Version < LanguageVersion.V_3)
- Report.FeatureIsNotAvailable (loc, "implicitly typed local variable");
+ rc.Compiler.Report.FeatureIsNotAvailable (loc, "implicitly typed local variable");
if (initializer == null)
return null;
if (initializer.Count > 1) {
Location loc_init = ((CSharpParser.VariableDeclaration) initializer[1]).Location;
- Report.Error (819, loc_init, "An implicitly typed local variable declaration cannot include multiple declarators");
+ rc.Compiler.Report.Error (819, loc_init, "An implicitly typed local variable declaration cannot include multiple declarators");
initializer = null;
return null;
}
Expression variable_initializer = ((CSharpParser.VariableDeclaration) initializer[0]).expression_or_array_initializer;
if (variable_initializer == null) {
- Report.Error (818, loc, "An implicitly typed local variable declarator must include an initializer");
+ rc.Compiler.Report.Error (818, loc, "An implicitly typed local variable declarator must include an initializer");
return null;
}
return null;
if (!IsValidEnumType (c.Type)) {
- Enum.Error_1008 (Location);
+ Enum.Error_1008 (Location, ec.Report);
return null;
}
{
this.base_type = type;
int accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
- ModFlags = Modifiers.Check (AllowedModifiers, mod_flags, accmods, Location);
+ ModFlags = Modifiers.Check (AllowedModifiers, mod_flags, accmods, Location, Report);
}
public void AddEnumMember (EnumMember em)
AddConstant (em);
}
- public static void Error_1008 (Location loc)
+ public static void Error_1008 (Location loc, Report Report)
{
Report.Error (1008, loc, "Type byte, sbyte, short, ushort, " +
"int, uint, long or ulong expected");
static Driver driver;
static bool inited;
+ static CompilerContext ctx = new CompilerContext (new Report (new ConsoleReportPrinter ()));
+
/// <summary>
/// Optional initialization for the Evaluator.
/// </summary>
if (inited)
return new string [0];
- driver = Driver.Create (args, false);
+ driver = Driver.Create (args, false, new ConsoleReportPrinter ());
if (driver == null)
throw new Exception ("Failed to create compiler driver with the given arguments");
+
+ RootContext.ToplevelTypes = new ModuleContainer (ctx, true);
driver.ProcessDefaultConfig ();
startup_files.Add (file.Path);
CompilerCallableEntryPoint.Reset ();
+ RootContext.ToplevelTypes = new ModuleContainer (ctx, true);
+
driver.LoadReferences ();
RootContext.EvalMode = true;
inited = true;
//
// PartialReset should not reset the core types, this is very redundant.
//
- if (!TypeManager.InitCoreTypes ())
+ if (!TypeManager.InitCoreTypes (ctx))
throw new Exception ("Failed to InitCoreTypes");
- TypeManager.InitOptionalCoreTypes ();
+ TypeManager.InitOptionalCoreTypes (ctx);
- Location.AddFile ("{interactive}");
+ Location.AddFile (null, "{interactive}");
Location.Initialize ();
current_debug_name = "interactive" + (count++) + ".dll";
if (Environment.GetEnvironmentVariable ("SAVE") != null){
- CodeGen.Init (current_debug_name, current_debug_name, false);
+ CodeGen.Init (current_debug_name, current_debug_name, false, ctx);
} else
- CodeGen.InitDynamic (current_debug_name);
+ CodeGen.InitDynamic (ctx, current_debug_name);
}
/// <summary>
object parser_result = parser.InteractiveResult;
if (!(parser_result is Class)){
- int errors = Report.Errors;
+ int errors = ctx.Report.Errors;
NamespaceEntry.VerifyAllUsing ();
- if (errors == Report.Errors)
+ if (errors == ctx.Report.Errors)
parser.CurrentNamespace.Extract (using_alias_list, using_list);
}
- compiled = CompileBlock (parser_result as Class, parser.undo);
+ compiled = CompileBlock (parser_result as Class, parser.undo, ctx.Report);
}
return null;
try {
RootContext.ResolveTree ();
- if (Report.Errors != 0)
+ if (ctx.Report.Errors != 0)
return null;
RootContext.PopulateTypes ();
- if (Report.Errors != 0)
+ if (ctx.Report.Errors != 0)
return null;
MethodOrOperator method = null;
//
static InputKind ToplevelOrStatement (SeekableStreamReader seekable)
{
- Tokenizer tokenizer = new Tokenizer (seekable, (CompilationUnit) Location.SourceFiles [0]);
+ Tokenizer tokenizer = new Tokenizer (seekable, (CompilationUnit) Location.SourceFiles [0], ctx);
int t = tokenizer.token ();
switch (t){
InputKind kind = ToplevelOrStatement (seekable);
if (kind == InputKind.Error){
if (mode == ParseMode.ReportErrors)
- Report.Error (-25, "Detection Parsing Error");
+ ctx.Report.Error (-25, "Detection Parsing Error");
partial_input = false;
return null;
}
}
seekable.Position = 0;
- CSharpParser parser = new CSharpParser (seekable, (CompilationUnit) Location.SourceFiles [0]);
- parser.ErrorOutput = Report.Stderr;
+ CSharpParser parser = new CSharpParser (seekable, (CompilationUnit) Location.SourceFiles [0], ctx);
if (kind == InputKind.StatementOrExpression){
parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
disable_error_reporting = false;
if (disable_error_reporting)
- Report.DisableReporting ();
+ ctx.Report.DisableReporting ();
try {
parser.parse ();
} finally {
- if (Report.Errors != 0){
+ if (ctx.Report.Errors != 0){
if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF)
partial_input = true;
}
if (disable_error_reporting)
- Report.EnableReporting ();
+ ctx.Report.EnableReporting ();
}
return parser;
}
static volatile bool invoking;
- static CompiledMethod CompileBlock (Class host, Undo undo)
+ static CompiledMethod CompileBlock (Class host, Undo undo, Report Report)
{
RootContext.ResolveTree ();
if (Report.Errors != 0){
RootContext.CloseTypes ();
if (Environment.GetEnvironmentVariable ("SAVE") != null)
- CodeGen.Save (current_debug_name, false);
+ CodeGen.Save (current_debug_name, false, Report);
if (host == null)
return null;
static public void LoadAssembly (string file)
{
lock (evaluator_lock){
- Driver.LoadAssembly (file, false);
- GlobalRootNamespace.Instance.ComputeNamespaces ();
+ driver.LoadAssembly (file, false);
+ GlobalRootNamespace.Instance.ComputeNamespaces (ctx);
}
}
{
lock (evaluator_lock){
GlobalRootNamespace.Instance.AddAssemblyReference (a);
- GlobalRootNamespace.Instance.ComputeNamespaces ();
+ GlobalRootNamespace.Instance.ComputeNamespaces (ctx);
}
}
return;
}
- string pkgout = Driver.GetPackageFlags (pkg, false);
+ string pkgout = Driver.GetPackageFlags (pkg, false, RootContext.ToplevelTypes.Compiler.Report);
if (pkgout == null)
return;
new NullLiteral (loc),
mg.CreateExpressionTree (ec));
- return CreateExpressionFactoryCall ("Call", args);
+ return CreateExpressionFactoryCall (ec, "Call", args);
}
protected override void CloneTo (CloneContext context, Expression target)
int value = ((IntConstant)e).Value;
if (value == int.MinValue) {
if (ec.ConstantCheckState) {
- ConstantFold.Error_CompileTimeOverflow (loc);
+ ConstantFold.Error_CompileTimeOverflow (ec, loc);
return null;
}
return e;
long value = ((LongConstant)e).Value;
if (value == long.MinValue) {
if (ec.ConstantCheckState) {
- ConstantFold.Error_CompileTimeOverflow (loc);
+ ConstantFold.Error_CompileTimeOverflow (ec, loc);
return null;
}
return e;
string method_name;
switch (Oper) {
case Operator.AddressOf:
- Error_PointerInsideExpressionTree ();
+ Error_PointerInsideExpressionTree (ec);
return null;
case Operator.UnaryNegation:
if (ec.HasSet (ResolveContext.Options.CheckedScope) && user_op == null && !IsFloat (type))
args.Add (new Argument (Expr.CreateExpressionTree (ec)));
if (user_op != null)
args.Add (new Argument (user_op.CreateExpressionTree (ec)));
- return CreateExpressionFactoryCall (method_name, args);
+ return CreateExpressionFactoryCall (ec, method_name, args);
}
static void CreatePredefinedOperatorsTable ()
Expression expr = ResolveOperator (ec, Expr);
if (expr == null)
- Error_OperatorCannotBeApplied (loc, OperName (Oper), Expr.Type);
+ Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
//
// Reduce unary operator on predefined types
Expr.EmitSideEffect (ec);
}
- public static void Error_OperatorCannotBeApplied (Location loc, string oper, Type t)
+ public static void Error_OperatorCannotBeApplied (ResolveContext ec, Location loc, string oper, Type t)
{
- Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
+ ec.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
oper, TypeManager.CSharpName (t));
}
Expression ResolveAddressOf (ResolveContext ec)
{
if (!ec.IsUnsafe)
- UnsafeError (loc);
+ UnsafeError (ec, loc);
Expr = Expr.DoResolveLValue (ec, EmptyExpression.UnaryAddress);
if (Expr == null || Expr.eclass != ExprClass.Variable) {
- Report.Error (211, loc, "Cannot take the address of the given expression");
+ ec.Report.Error (211, loc, "Cannot take the address of the given expression");
return null;
}
vr.SetHasAddressTaken ();
if (vr.IsHoisted) {
- AnonymousMethodExpression.Error_AddressOfCapturedVar (vr, loc);
+ AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, vr, loc);
}
} else {
IFixedExpression fe = Expr as IFixedExpression;
}
if (!is_fixed && !ec.HasSet (ResolveContext.Options.FixedInitializerScope)) {
- Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
+ ec.Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
}
type = TypeManager.GetPointerType (Expr.Type);
}
string op_name = CSharp.Operator.GetMetadataName (op_type);
- MethodGroupExpr user_op = MemberLookup (ec.CurrentType, expr.Type, op_name, MemberTypes.Method, AllBindingFlags, expr.Location) as MethodGroupExpr;
+ MethodGroupExpr user_op = MemberLookup (ec.Compiler, ec.CurrentType, expr.Type, op_name, MemberTypes.Method, AllBindingFlags, expr.Location) as MethodGroupExpr;
if (user_op == null)
return null;
int result = MethodGroupExpr.BetterTypeConversion (ec, best_expr.Type, t);
if (result == 0) {
- Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
+ ec.Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
OperName (Oper), TypeManager.CSharpName (expr.Type));
break;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
- Error_PointerInsideExpressionTree ();
+ Error_PointerInsideExpressionTree (ec);
return null;
}
return null;
if (!ec.IsUnsafe)
- UnsafeError (loc);
+ UnsafeError (ec, loc);
if (!expr.Type.IsPointer) {
- Report.Error (193, loc, "The * or -> operator must be applied to a pointer");
+ ec.Report.Error (193, loc, "The * or -> operator must be applied to a pointer");
return null;
}
if (expr.Type == TypeManager.void_ptr_type) {
- Report.Error (242, loc, "The operation in question is undefined on void pointers");
+ ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
return null;
}
if (expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess) {
expr = expr.ResolveLValue (ec, expr);
} else {
- Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
+ ec.Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
}
//
else
op_name = Operator.GetMetadataName (Operator.OpType.Decrement);
- mg = MemberLookup (ec.CurrentType, type, op_name, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
+ mg = MemberLookup (ec.Compiler, ec.CurrentType, type, op_name, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
if (mg != null) {
Arguments args = new Arguments (1);
}
if (!IsIncrementableNumber (type)) {
- Report.Error (187, loc, "No such operator '" + OperName (mode) + "' defined for type '" +
+ ec.Report.Error (187, loc, "No such operator '" + OperName (mode) + "' defined for type '" +
TypeManager.CSharpName (type) + "'");
return null;
}
return null;
if ((probe_type_expr.Type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
- Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
+ ec.Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
OperatorName);
}
if (expr.Type.IsPointer || probe_type_expr.Type.IsPointer) {
- Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
+ ec.Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
OperatorName);
return null;
}
if (expr.Type == InternalType.AnonymousMethod) {
- Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression or anonymous method",
+ ec.Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression or anonymous method",
OperatorName);
return null;
}
expr.CreateExpressionTree (ec),
new TypeOf (probe_type_expr, loc));
- return CreateExpressionFactoryCall ("TypeIs", args);
+ return CreateExpressionFactoryCall (ec, "TypeIs", args);
}
public override void Emit (EmitContext ec)
ig.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
}
- Expression CreateConstantResult (bool result)
+ Expression CreateConstantResult (ResolveContext ec, bool result)
{
if (result)
- Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
+ ec.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
TypeManager.CSharpName (probe_type_expr.Type));
else
- Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
+ ec.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
TypeManager.CSharpName (probe_type_expr.Type));
return ReducedExpression.Create (new BoolConstant (result, loc), this);
// type or a nullable type and the value of E is null, the result is false
//
if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
- return CreateConstantResult (false);
+ return CreateConstantResult (ec, false);
if (TypeManager.IsNullableType (d) && !TypeManager.ContainsGenericParameters (d)) {
d = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (d) [0]);
//
// The result is true if D and T are the same value types
//
- return CreateConstantResult (true);
+ return CreateConstantResult (ec, true);
}
if (TypeManager.IsGenericParameter (d))
- return ResolveGenericParameter (t, d);
+ return ResolveGenericParameter (ec, t, d);
//
// An unboxing conversion exists
return this;
} else {
if (TypeManager.IsGenericParameter (t))
- return ResolveGenericParameter (d, t);
+ return ResolveGenericParameter (ec, d, t);
if (TypeManager.IsStruct (d)) {
bool temp;
if (Convert.ImplicitBoxingConversionExists (expr, t, out temp))
- return CreateConstantResult (true);
+ return CreateConstantResult (ec, true);
} else {
if (TypeManager.IsGenericParameter (d))
- return ResolveGenericParameter (t, d);
+ return ResolveGenericParameter (ec, t, d);
if (TypeManager.ContainsGenericParameters (d))
return this;
}
}
- return CreateConstantResult (false);
+ return CreateConstantResult (ec, false);
}
- Expression ResolveGenericParameter (Type d, Type t)
+ Expression ResolveGenericParameter (ResolveContext ec, Type d, Type t)
{
GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
if (constraints != null) {
if (constraints.IsReferenceType && TypeManager.IsStruct (d))
- return CreateConstantResult (false);
+ return CreateConstantResult (ec, false);
if (constraints.IsValueType && !TypeManager.IsStruct (d))
- return CreateConstantResult (TypeManager.IsEqual (d, t));
+ return CreateConstantResult (ec, TypeManager.IsEqual (d, t));
}
if (TypeManager.IsGenericParameter (expr.Type))
expr.CreateExpressionTree (ec),
new TypeOf (probe_type_expr, loc));
- return CreateExpressionFactoryCall ("TypeAs", args);
+ return CreateExpressionFactoryCall (ec, "TypeAs", args);
}
public override void Emit (EmitContext ec)
if (!TypeManager.IsReferenceType (type) && !TypeManager.IsNullableType (type)) {
if (TypeManager.IsGenericParameter (type)) {
- Report.Error (413, loc,
+ ec.Report.Error (413, loc,
"The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
probe_type_expr.GetSignatureForError ());
} else {
- Report.Error (77, loc,
+ ec.Report.Error (77, loc,
"The `as' operator cannot be used with a non-nullable value type `{0}'",
TypeManager.CSharpName (type));
}
}
if (expr.IsNull && TypeManager.IsNullableType (type)) {
- return Nullable.LiftedNull.CreateFromExpression (this);
+ return Nullable.LiftedNull.CreateFromExpression (ec, this);
}
Expression e = Convert.ImplicitConversion (ec, expr, type, loc);
return this;
}
- Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
+ ec.Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
TypeManager.CSharpName (etype), TypeManager.CSharpName (type));
return null;
type = target.Type;
if (type.IsAbstract && type.IsSealed) {
- Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
+ ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
return null;
}
}
if (type.IsPointer && !ec.IsUnsafe) {
- UnsafeError (loc);
+ UnsafeError (ec, loc);
} else if (TypeManager.IsDynamicType (expr.Type)) {
Arguments arg = new Arguments (1);
arg.Add (new Argument (expr));
Arguments args = new Arguments (2);
args.Add (new Argument (this));
args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
- return CreateExpressionFactoryCall ("Constant", args);
+ return CreateExpressionFactoryCall (ec, "Constant", args);
}
public override Expression DoResolve (ResolveContext ec)
type = texpr.Type;
if ((type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
- Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
+ ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
}
if (type.IsPointer)
return s;
}
- public static void Error_OperatorCannotBeApplied (Expression left, Expression right, Operator oper, Location loc)
+ public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
{
- new Binary (oper, left, right).Error_OperatorCannotBeApplied (left, right);
+ new Binary (oper, left, right).Error_OperatorCannotBeApplied (ec, left, right);
}
- public static void Error_OperatorCannotBeApplied (Expression left, Expression right, string oper, Location loc)
+ public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
{
string l, r;
l = TypeManager.CSharpName (left.Type);
r = TypeManager.CSharpName (right.Type);
- Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
+ ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
oper, l, r);
}
- protected void Error_OperatorCannotBeApplied (Expression left, Expression right)
+ protected void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
{
- Error_OperatorCannotBeApplied (left, right, OperName (oper), loc);
+ Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
}
//
break;
return left;
}
- Error_OperatorCannotBeApplied (this.left, this.right);
+ Error_OperatorCannotBeApplied (ec, this.left, this.right);
return null;
}
//
// The `|' operator used on types which were extended is dangerous
//
- void CheckBitwiseOrOnSignExtended ()
+ void CheckBitwiseOrOnSignExtended (ResolveContext ec)
{
OpcodeCast lcast = left as OpcodeCast;
if (lcast != null) {
// FIXME: consider constants
- Report.Warning (675, 3, loc,
+ ec.Report.Warning (675, 3, loc,
"The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
TypeManager.CSharpName (lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType));
}
return null;
if (left.eclass == ExprClass.Type) {
- Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
+ ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
return null;
}
} else
// FIXME: resolve right expression as unreachable
// right.Resolve (ec);
- Report.Warning (429, 4, loc, "Unreachable expression code detected");
+ ec.Report.Warning (429, 4, loc, "Unreachable expression code detected");
return left;
}
}
if (rc != null && lc != null) {
- int prev_e = Report.Errors;
+ int prev_e = ec.Report.Errors;
Expression e = ConstantFold.BinaryFold (
ec, oper, lc, rc, loc);
- if (e != null || Report.Errors != prev_e)
+ if (e != null || ec.Report.Errors != prev_e)
return e;
} else if ((oper == Operator.BitwiseAnd || oper == Operator.LogicalAnd) && !TypeManager.IsDynamicType (left.Type) &&
((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue))) {
if ((ResolveOperator (ec)) == null) {
- Error_OperatorCannotBeApplied (left, right);
+ Error_OperatorCannotBeApplied (ec, left, right);
return null;
}
// Comparison warnings
if ((oper & Operator.ComparisonMask) != 0) {
if (left.Equals (right)) {
- Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
+ ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
}
- CheckUselessComparison (lc, right.Type);
- CheckUselessComparison (rc, left.Type);
+ CheckUselessComparison (ec, lc, right.Type);
+ CheckUselessComparison (ec, rc, left.Type);
}
if (TypeManager.IsDynamicType (left.Type) || TypeManager.IsDynamicType (right.Type)) {
{
Expression expr = ResolveOperator (ec);
if (expr == null)
- Error_OperatorCannotBeApplied (left_orig, right_orig);
+ Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
if (left == null || right == null)
throw new InternalErrorException ("Invalid conversion");
if (oper == Operator.BitwiseOr)
- CheckBitwiseOrOnSignExtended ();
+ CheckBitwiseOrOnSignExtended (ec);
return expr;
}
//
if (Convert.ImplicitReferenceConversionExists (left, r)) {
if (l == TypeManager.string_type)
- Report.Warning (253, 2, loc, ref_comparison, "right");
+ ec.Report.Warning (253, 2, loc, ref_comparison, "right");
return this;
}
if (Convert.ImplicitReferenceConversionExists (right, l)) {
if (r == TypeManager.string_type)
- Report.Warning (252, 2, loc, ref_comparison, "left");
+ ec.Report.Warning (252, 2, loc, ref_comparison, "left");
return this;
}
best_operator = po.ResolveBetterOperator (ec, best_operator);
if (best_operator == null) {
- Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
+ ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
OperName (oper), left.GetSignatureForError (), right.GetSignatureForError ());
best_operator = po;
string op = GetOperatorMetadataName (user_oper);
- MethodGroupExpr left_operators = MemberLookup (ec.CurrentType, l, op, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
+ MethodGroupExpr left_operators = MemberLookup (ec.Compiler, ec.CurrentType, l, op, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
MethodGroupExpr right_operators = null;
if (!TypeManager.IsEqual (r, l)) {
- right_operators = MemberLookup (ec.CurrentType, r, op, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
+ right_operators = MemberLookup (ec.Compiler, ec.CurrentType, r, op, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
if (right_operators == null && left_operators == null)
return null;
} else if (left_operators == null) {
return null;
}
- private void CheckUselessComparison (Constant c, Type type)
+ private void CheckUselessComparison (ResolveContext ec, Constant c, Type type)
{
if (c == null || !IsTypeIntegral (type)
|| c is StringConstant
type == TypeManager.uint32_type ||
type == TypeManager.int64_type ||
type == TypeManager.char_type)
- WarnUselessComparison (type);
+ WarnUselessComparison (ec, type);
return;
}
value = (long) uvalue;
return;
if (IsValueOutOfRange (value, type))
- WarnUselessComparison (type);
+ WarnUselessComparison (ec, type);
}
static bool IsValueOutOfRange (long value, Type type)
type == TypeManager.char_type;
}
- private void WarnUselessComparison (Type type)
+ private void WarnUselessComparison (ResolveContext ec, Type type)
{
- Report.Warning (652, 2, loc, "A comparison between a constant and a variable is useless. The constant is out of the range of the variable type `{0}'",
+ ec.Report.Warning (652, 2, loc, "A comparison between a constant and a variable is useless. The constant is out of the range of the variable type `{0}'",
TypeManager.CSharpName (type));
}
args.Add (new Argument (method.CreateExpressionTree (ec)));
}
- return CreateExpressionFactoryCall (method_name, args);
+ return CreateExpressionFactoryCall (ec, method_name, args);
}
}
add_args.Add (new Argument (method.CreateExpressionTree (ec)));
- Expression expr = CreateExpressionFactoryCall ("Add", add_args);
+ Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
if (++pos == arguments.Count)
return expr;
type = TypeManager.TypeToCoreType (method.ReturnType);
AParametersCollection pd = TypeManager.GetParameterData (method);
if (!TypeManager.IsEqual (type, type) || !TypeManager.IsEqual (type, pd.Types [0]) || !TypeManager.IsEqual (type, pd.Types [1])) {
- Report.Error (217, loc,
+ ec.Report.Error (217, loc,
"A user-defined operator `{0}' must have parameters and return values of the same type in order to be applicable as a short circuit operator",
TypeManager.CSharpSignature (method));
return null;
Expression op_true = GetOperatorTrue (ec, left_dup, loc);
Expression op_false = GetOperatorFalse (ec, left_dup, loc);
if (op_true == null || op_false == null) {
- Report.Error (218, loc,
+ ec.Report.Error (218, loc,
"The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
TypeManager.CSharpName (type), TypeManager.CSharpSignature (method));
return null;
public override Expression CreateExpressionTree (ResolveContext ec)
{
- Error_PointerInsideExpressionTree ();
+ Error_PointerInsideExpressionTree (ec);
return null;
}
eclass = ExprClass.Variable;
if (left.Type == TypeManager.void_ptr_type) {
- Report.Error (242, loc, "The operation in question is undefined on void pointers");
+ ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
return null;
}
args.Add (new Argument (expr.CreateExpressionTree (ec)));
args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
- return CreateExpressionFactoryCall ("Condition", args);
+ return CreateExpressionFactoryCall (ec, "Condition", args);
}
public override Expression DoResolve (ResolveContext ec)
Assign ass = expr as Assign;
if (ass != null && ass.Source is Constant) {
- Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
+ ec.Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
}
true_expr = true_expr.Resolve (ec);
// Check if both can convert implicitl to each other's type
//
if (Convert.ImplicitConversion (ec, false_expr, true_type, loc) != null) {
- Report.Error (172, loc,
+ ec.Report.Error (172, loc,
"Can not compute type of conditional expression " +
"as `" + TypeManager.CSharpName (true_expr.Type) +
"' and `" + TypeManager.CSharpName (false_expr.Type) +
} else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
false_expr = conv;
} else {
- Report.Error (173, loc,
+ ec.Report.Error (173, loc,
"Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
true_expr.GetSignatureForError (), false_expr.GetSignatureForError ());
return null;
Constant c = expr as Constant;
if (c != null){
bool is_false = c.IsDefaultValue;
- Report.Warning (429, 4, is_false ? true_expr.Location : false_expr.Location, "Unreachable expression code detected");
+ ec.Report.Warning (429, 4, is_false ? true_expr.Location : false_expr.Location, "Unreachable expression code detected");
return ReducedExpression.Create (is_false ? false_expr : true_expr, this).Resolve (ec);
}
Arguments arg = new Arguments (1);
arg.Add (new Argument (this));
- return CreateExpressionFactoryCall ("Constant", arg);
+ return CreateExpressionFactoryCall (ec, "Constant", arg);
}
Expression DoResolveBase (ResolveContext ec)
//
if (ec.MustCaptureVariable (local_info)) {
if (local_info.AddressTaken)
- AnonymousMethodExpression.Error_AddressOfCapturedVar (this, loc);
+ AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
if (ec.IsVariableCapturingRequired) {
AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
if (type == null && local_info.Type is VarExpr) {
local_info.VariableType = TypeManager.object_type;
- Error_VariableIsUsedBeforeItIsDeclared (Name);
+ Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
return null;
}
} else {
code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
}
- Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
+ ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
} else if (VariableInfo != null) {
VariableInfo.SetAssigned (ec);
}
if (!ec.DoFlowAnalysis || !HasOutModifier || ec.CurrentBranching.IsAssigned (VariableInfo))
return true;
- Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
+ ec.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
return false;
}
return true;
if (IsRef) {
- Report.Error (1628, loc,
+ ec.Report.Error (1628, loc,
"Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
Name, am.ContainerType);
}
}
if (pi.Parameter.HasAddressTaken)
- AnonymousMethodExpression.Error_AddressOfCapturedVar (this, loc);
+ AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
if (ec.IsVariableCapturingRequired) {
AnonymousMethodStorey storey = pi.Block.CreateAnonymousMethodStorey (ec);
if (TypeManager.DropGenericTypeArguments (type) == TypeManager.expression_type) {
args = new Arguments (1);
args.Add (new Argument (this));
- return CreateExpressionFactoryCall ("Quote", args);
+ return CreateExpressionFactoryCall (ec, "Quote", args);
}
Expression instance = mg.IsInstance ?
mg.CreateExpressionTree (ec));
if (mg.IsBase)
- MemberExpr.Error_BaseAccessInExpressionTree (loc);
+ MemberExpr.Error_BaseAccessInExpressionTree (ec, loc);
- return CreateExpressionFactoryCall ("Call", args);
+ return CreateExpressionFactoryCall (ec, "Call", args);
}
public override Expression DoResolve (ResolveContext ec)
expr = null;
} else {
if (mg.IsBase) {
- Report.Error (1971, loc,
+ ec.Report.Error (1971, loc,
"The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
mg.Name);
return null;
MemberExpr me = expr_resolved as MemberExpr;
if (me == null) {
- expr_resolved.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
+ expr_resolved.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
return null;
}
mg = ec.LookupExtensionMethod (me.Type, me.Name, loc);
if (mg == null) {
- Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
+ ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
expr_resolved.GetSignatureForError ());
return null;
}
mg.IdenticalTypeName) {
mg.InstanceExpression = null;
} else {
- MemberExpr.error176 (loc, mg.GetSignatureForError ());
+ MemberExpr.error176 (ec, loc, mg.GetSignatureForError ());
return null;
}
} else {
if (type.IsPointer){
if (!ec.IsUnsafe){
- UnsafeError (loc);
+ UnsafeError (ec, loc);
return null;
}
}
// Only base will allow this invocation to happen.
//
if (mg.IsBase && method.IsAbstract){
- Error_CannotCallAbstractBase (TypeManager.CSharpSignature (method));
+ Error_CannotCallAbstractBase (ec, TypeManager.CSharpSignature (method));
return null;
}
if (arguments == null && method.DeclaringType == TypeManager.object_type && method.Name == Destructor.MetadataName) {
if (mg.IsBase)
- Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
+ ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
else
- Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
+ ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
return null;
}
- IsSpecialMethodInvocation (method, loc);
+ IsSpecialMethodInvocation (ec, method, loc);
if (mg.InstanceExpression != null)
mg.InstanceExpression.CheckMarshalByRefAccess (ec);
return mg.OverloadResolve (ec, ref arguments, false, loc);
}
- public static bool IsSpecialMethodInvocation (MethodBase method, Location loc)
+ public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodBase method, Location loc)
{
if (!TypeManager.IsSpecialMethod (method))
return false;
- Report.SymbolRelatedToPreviousError (method);
- Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
+ ec.Report.SymbolRelatedToPreviousError (method);
+ ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
TypeManager.CSharpSignature (method, true));
return true;
method.CreateExpressionTree (ec));
}
- return CreateExpressionFactoryCall ("New", args);
+ return CreateExpressionFactoryCall (ec, "New", args);
}
public override Expression DoResolve (ResolveContext ec)
type = texpr.Type;
if (type.IsPointer) {
- Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
+ ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
TypeManager.CSharpName (type));
return null;
}
GenericConstraints gc = TypeManager.GetTypeParameterConstraints (type);
if ((gc == null) || (!gc.HasConstructorConstraint && !gc.IsValueType)) {
- Report.Error (304, loc,
+ ec.Report.Error (304, loc,
"Cannot create an instance of the variable type '{0}' because it doesn't have the new() constraint",
TypeManager.CSharpName (type));
return null;
}
if ((Arguments != null) && (Arguments.Count != 0)) {
- Report.Error (417, loc,
+ ec.Report.Error (417, loc,
"`{0}': cannot provide arguments when creating an instance of a variable type",
TypeManager.CSharpName (type));
return null;
}
if (TypeManager.activator_create_instance == null) {
- Type activator_type = TypeManager.CoreLookupType ("System", "Activator", Kind.Class, true);
+ Type activator_type = TypeManager.CoreLookupType (ec.Compiler, "System", "Activator", Kind.Class, true);
if (activator_type != null) {
TypeManager.activator_create_instance = TypeManager.GetPredefinedMethod (
activator_type, "CreateInstance", loc, Type.EmptyTypes);
}
if (type.IsAbstract && type.IsSealed) {
- Report.SymbolRelatedToPreviousError (type);
- Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
+ ec.Report.SymbolRelatedToPreviousError (type);
+ ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
return null;
}
return RequestedType;
}
- Report.SymbolRelatedToPreviousError (type);
- Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
+ ec.Report.SymbolRelatedToPreviousError (type);
+ ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
return null;
}
method = ml as MethodGroupExpr;
if (method == null) {
- ml.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
+ ml.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
return null;
}
expect_initializers = true;
}
- protected override void Error_NegativeArrayIndex (Location loc)
+ protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
{
- Report.Error (248, loc, "Cannot create an array with a negative size");
+ ec.Report.Error (248, loc, "Cannot create an array with a negative size");
}
bool CheckIndices (ResolveContext ec, ArrayList probe, int idx, bool specified_dims, int child_bounds)
}
if (c == null) {
- Report.Error (150, a.Location, "A constant value is expected");
+ ec.Report.Error (150, a.Location, "A constant value is expected");
return false;
}
int value = (int) c.GetValue ();
if (value != probe.Count) {
- Report.Error (847, loc, "An array initializer of length `{0}' was expected", value);
+ ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value);
return false;
}
if (o is ArrayList) {
ArrayList sub_probe = o as ArrayList;
if (idx + 1 >= dimensions){
- Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
+ ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
return false;
}
if (!ret)
return false;
} else if (child_bounds > 1) {
- Report.Error (846, ((Expression) o).Location, "A nested array initializer was expected");
+ ec.Report.Error (846, ((Expression) o).Location, "A nested array initializer was expected");
} else {
Expression element = ResolveArrayElement (ec, (Expression) o);
if (element == null)
if (arguments.Count == 1) {
Constant c = a as Constant;
if (c.IsDefaultValue)
- return CreateExpressionFactoryCall ("NewArrayInit", args);
+ return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
}
args.Add (new Argument (a.CreateExpressionTree (ec)));
}
- return CreateExpressionFactoryCall ("NewArrayBounds", args);
+ return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
}
if (dimensions > 1) {
- Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
+ ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
return null;
}
}
}
- return CreateExpressionFactoryCall ("NewArrayInit", args);
+ return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
}
public void UpdateIndices ()
bool ResolveArrayType (ResolveContext ec)
{
if (requested_base_type == null) {
- Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
+ ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
return false;
}
if (requested_base_type is VarExpr) {
- Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
+ ec.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
return false;
}
arg_types);
if (mi == null) {
- Report.Error (-6, "New invocation: Can not find a constructor for " +
+ RootContext.ToplevelTypes.Compiler.Report.Error (-6, "New invocation: Can not find a constructor for " +
"this argument list");
return null;
}
public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
{
if (arguments.Count != 1) {
- // Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
+ // ec.Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
return base.GetAttributableValue (ec, null, out value);
}
value = Array.CreateInstance (array_element_type, 0);
return true;
}
- // Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
+ // ec.Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
return base.GetAttributableValue (ec, null, out value);
}
if (array_element_type == null || array_element_type == TypeManager.null_type ||
array_element_type == TypeManager.void_type || array_element_type == InternalType.AnonymousMethod ||
arguments.Count != dimensions) {
- Error_NoBestType ();
+ Error_NoBestType (ec);
return null;
}
return this;
}
- void Error_NoBestType ()
+ void Error_NoBestType (ResolveContext ec)
{
- Report.Error (826, loc,
+ ec.Report.Error (826, loc,
"The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
}
return element;
}
- Error_NoBestType ();
+ Error_NoBestType (ec);
return null;
}
}
if (!IsThisAvailable (ec)) {
if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
- Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
+ ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
} else if (ec.CurrentAnonymousMethod != null) {
- Report.Error (1673, loc,
+ ec.Report.Error (1673, loc,
"Anonymous methods inside structs cannot access instance members of `this'. " +
"Consider copying `this' to a local variable outside the anonymous method and using the local instead");
} else {
- Report.Error (27, loc, "Keyword `this' is not available in the current context");
+ ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
}
}
{
if ((variable_info != null) && !(TypeManager.IsStruct (type) && ec.OmitStructFlowAnalysis) &&
!variable_info.IsAssigned (ec)) {
- Report.Error (188, loc,
+ ec.Report.Error (188, loc,
"The `this' object cannot be used before all of its fields are assigned to");
variable_info.SetAssigned (ec);
}
// Use typeless constant for ldarg.0 to save some
// space and avoid problems with anonymous stories
- return CreateExpressionFactoryCall ("Constant", args);
+ return CreateExpressionFactoryCall (ec, "Constant", args);
}
public override Expression DoResolve (ResolveContext ec)
if (ec.CurrentType.IsClass){
if (right_side == EmptyExpression.UnaryAddress)
- Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
+ ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
else if (right_side == EmptyExpression.OutAccess)
- Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
+ ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
else
- Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
+ ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
}
return this;
type = TypeManager.runtime_argument_handle_type;
if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.Toplevel.Parameters.HasArglist) {
- Report.Error (190, loc,
+ ec.Report.Error (190, loc,
"The __arglist construct is valid only within a variable argument method");
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
- Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
+ ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
return null;
}
Arguments args = new Arguments (2);
args.Add (new Argument (this));
args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
- return CreateExpressionFactoryCall ("Constant", args);
+ return CreateExpressionFactoryCall (ec, "Constant", args);
}
public override Expression DoResolve (ResolveContext ec)
typearg = texpr.Type;
if (typearg == TypeManager.void_type) {
- Report.Error (673, loc, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
+ ec.Report.Error (673, loc, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
} else if (typearg.IsPointer && !ec.IsUnsafe){
- UnsafeError (loc);
+ UnsafeError (ec, loc);
} else if (texpr is DynamicTypeExpr) {
- Report.Error (1962, QueriedType.Location,
+ ec.Report.Error (1962, QueriedType.Location,
"The typeof operator cannot be used on the dynamic type");
}
{
if (TypeManager.ContainsGenericParameters (typearg) &&
!TypeManager.IsGenericTypeDefinition (typearg)) {
- Report.SymbolRelatedToPreviousError (typearg);
- Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
+ ec.Report.SymbolRelatedToPreviousError (typearg);
+ ec.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
TypeManager.CSharpName (typearg));
value = null;
return false;
if (member is MethodInfo) {
type = TypeManager.methodinfo_type;
if (type == null)
- type = TypeManager.methodinfo_type = TypeManager.CoreLookupType ("System.Reflection", "MethodInfo", Kind.Class, true);
+ type = TypeManager.methodinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "MethodInfo", Kind.Class, true);
} else {
type = TypeManager.ctorinfo_type;
if (type == null)
- type = TypeManager.ctorinfo_type = TypeManager.CoreLookupType ("System.Reflection", "ConstructorInfo", Kind.Class, true);
+ type = TypeManager.ctorinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "ConstructorInfo", Kind.Class, true);
}
return base.DoResolve (ec);
Arguments args = new Arguments (2);
args.Add (new Argument (this));
args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
- return CreateExpressionFactoryCall ("Constant", args);
+ return CreateExpressionFactoryCall (ec, "Constant", args);
}
public override Expression DoResolve (ResolveContext ec)
MethodInfo mi = is_generic ? TypeFromHandleGeneric : TypeFromHandle;
if (mi == null) {
- Type t = TypeManager.CoreLookupType ("System.Reflection", TypeName, Kind.Class, true);
- Type handle_type = TypeManager.CoreLookupType ("System", RuntimeHandleName, Kind.Class, true);
+ Type t = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, Kind.Class, true);
+ Type handle_type = TypeManager.CoreLookupType (ec.Compiler, "System", RuntimeHandleName, Kind.Class, true);
if (t == null || handle_type == null)
return null;
public override Expression DoResolve (ResolveContext ec)
{
if (TypeManager.fieldinfo_type == null)
- TypeManager.fieldinfo_type = TypeManager.CoreLookupType ("System.Reflection", TypeName, Kind.Class, true);
+ TypeManager.fieldinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, Kind.Class, true);
type = TypeManager.fieldinfo_type;
return base.DoResolve (ec);
public override Expression CreateExpressionTree (ResolveContext ec)
{
- Error_PointerInsideExpressionTree ();
+ Error_PointerInsideExpressionTree (ec);
return null;
}
}
if (!ec.IsUnsafe) {
- Report.Error (233, loc,
+ ec.Report.Error (233, loc,
"`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
TypeManager.CSharpName (type_queried));
}
return base.ResolveAsTypeStep (ec, silent);
}
- int errors = Report.Errors;
+ int errors = ec.Compiler.Report.Errors;
expr = ec.LookupNamespaceAlias (alias);
if (expr == null) {
- if (errors == Report.Errors)
- Report.Error (432, loc, "Alias `{0}' not found", alias);
+ if (errors == ec.Compiler.Report.Errors)
+ ec.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
return null;
}
if (expr.eclass == ExprClass.Type) {
if (!silent) {
- Report.Error (431, loc,
+ ec.Compiler.Report.Error (431, loc,
"Alias `{0}' cannot be used with '::' since it denotes a type. Consider replacing '::' with '.'", alias);
}
return null;
protected override void Error_IdentifierNotFound (IMemberContext rc, FullNamedExpression expr_type, string identifier)
{
- Report.Error (687, loc,
+ rc.Compiler.Report.Error (687, loc,
"A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
GetSignatureForError ());
}
Namespace ns = expr_resolved as Namespace;
if (ns != null) {
- FullNamedExpression retval = ns.Lookup (LookupIdentifier, loc);
+ FullNamedExpression retval = ns.Lookup (ec.Compiler, LookupIdentifier, loc);
if (retval == null)
- ns.Error_NamespaceDoesNotExist (loc, LookupIdentifier);
+ ns.Error_NamespaceDoesNotExist (loc, LookupIdentifier, ec.Report);
else if (targs != null)
retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (ec, false);
if (expr_type.IsPointer || expr_type == TypeManager.void_type ||
expr_type == TypeManager.null_type || expr_type == InternalType.AnonymousMethod) {
- Unary.Error_OperatorCannotBeApplied (loc, ".", expr_type);
+ Unary.Error_OperatorCannotBeApplied (ec, loc, ".", expr_type);
return null;
}
Constant c = expr_resolved as Constant;
if (c != null && c.GetValue () == null) {
- Report.Warning (1720, 1, loc, "Expression will always cause a `{0}'",
+ ec.Report.Warning (1720, 1, loc, "Expression will always cause a `{0}'",
"System.NullReferenceException");
}
}
Expression member_lookup;
- member_lookup = MemberLookup (
+ member_lookup = MemberLookup (ec.Compiler,
ec.CurrentType, expr_type, expr_type, Name, loc);
if (member_lookup == null && targs != null) {
- member_lookup = MemberLookup (
+ member_lookup = MemberLookup (ec.Compiler,
ec.CurrentType, expr_type, expr_type, LookupIdentifier, loc);
}
ex_method_lookup.ExtensionExpression = expr_resolved;
if (targs != null) {
- ex_method_lookup.SetTypeArguments (targs);
+ ex_method_lookup.SetTypeArguments (ec, targs);
}
return ex_method_lookup.DoResolve (ec);
}
expr = expr_resolved;
- member_lookup = Error_MemberLookupFailed (
+ member_lookup = Error_MemberLookupFailed (ec,
ec.CurrentType, expr_type, expr_type, Name, null,
AllMemberTypes, AllBindingFlags);
if (member_lookup == null)
if (texpr != null) {
if (!(expr_resolved is TypeExpr) &&
(original == null || !original.IdenticalNameAndTypeName (ec, expr_resolved, loc))) {
- Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
+ ec.Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
Name, member_lookup.GetSignatureForError ());
return null;
}
if (!texpr.CheckAccessLevel (ec.MemberContext)) {
- Report.SymbolRelatedToPreviousError (member_lookup.Type);
- ErrorIsInaccesible (loc, TypeManager.CSharpName (member_lookup.Type));
+ ec.Report.SymbolRelatedToPreviousError (member_lookup.Type);
+ ErrorIsInaccesible (loc, TypeManager.CSharpName (member_lookup.Type), ec.Report);
return null;
}
return null;
if (targs != null) {
- me.SetTypeArguments (targs);
+ me.SetTypeArguments (ec, targs);
}
if (original != null && !TypeManager.IsValueType (expr_type)) {
Namespace ns = expr_resolved as Namespace;
if (ns != null) {
- FullNamedExpression retval = ns.Lookup (LookupIdentifier, loc);
+ FullNamedExpression retval = ns.Lookup (rc.Compiler, LookupIdentifier, loc);
if (retval == null && !silent)
- ns.Error_NamespaceDoesNotExist (loc, LookupIdentifier);
+ ns.Error_NamespaceDoesNotExist (loc, LookupIdentifier, rc.Compiler.Report);
else if (targs != null)
retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (rc, silent);
Type expr_type = tnew_expr.Type;
if (TypeManager.IsGenericParameter (expr_type)) {
- Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
+ rc.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
tnew_expr.GetSignatureForError ());
return null;
}
- Expression member_lookup = MemberLookup (
+ Expression member_lookup = MemberLookup (rc.Compiler,
rc.CurrentType, expr_type, expr_type, LookupIdentifier,
MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic, loc);
if (member_lookup == null) {
protected virtual void Error_IdentifierNotFound (IMemberContext rc, FullNamedExpression expr_type, string identifier)
{
- Expression member_lookup = MemberLookup (
+ Expression member_lookup = MemberLookup (rc.Compiler,
rc.CurrentType, expr_type.Type, expr_type.Type, SimpleName.RemoveGenericArity (identifier),
MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic, loc);
return;
}
- member_lookup = MemberLookup (
+ member_lookup = MemberLookup (rc.Compiler,
rc.CurrentType, expr_type.Type, expr_type.Type, identifier,
MemberTypes.All, BindingFlags.Public | BindingFlags.NonPublic, loc);
if (member_lookup == null) {
- Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
+ rc.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
Name, expr_type.GetSignatureForError ());
} else {
// TODO: Report.SymbolRelatedToPreviousError
- member_lookup.Error_UnexpectedKind (null, "type", loc);
+ member_lookup.Error_UnexpectedKind (rc.Compiler.Report, null, "type", loc);
}
}
- protected override void Error_TypeDoesNotContainDefinition (Type type, string name)
+ protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, Type type, string name)
{
if (RootContext.Version > LanguageVersion.ISO_2 &&
((expr.eclass & (ExprClass.Value | ExprClass.Variable)) != 0)) {
- Report.Error (1061, loc, "Type `{0}' does not contain a definition for `{1}' and no " +
+ ec.Report.Error (1061, loc, "Type `{0}' does not contain a definition for `{1}' and no " +
"extension method `{1}' of type `{0}' could be found " +
"(are you missing a using directive or an assembly reference?)",
TypeManager.CSharpName (type), name);
return;
}
- base.Error_TypeDoesNotContainDefinition (type, name);
+ base.Error_TypeDoesNotContainDefinition (ec, type, name);
}
public override string GetSignatureForError ()
Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
Expr.CreateExpressionTree (ec));
- return CreateExpressionFactoryCall ("ArrayIndex", args);
+ return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
}
Expression MakePointerAccess (ResolveContext ec, Type t)
{
if (Arguments.Count != 1){
- Report.Error (196, loc, "A pointer must be indexed by only one value");
+ ec.Report.Error (196, loc, "A pointer must be indexed by only one value");
return null;
}
if (Arguments [0] is NamedArgument)
- Error_NamedArgument ((NamedArgument) Arguments[0]);
+ Error_NamedArgument ((NamedArgument) Arguments[0], ec.Report);
Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, Arguments [0].Expr.Resolve (ec), t, loc);
return new Indirection (p, loc).Resolve (ec);
Type t = Expr.Type;
if (t == TypeManager.array_type){
- Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
+ ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
return null;
}
throw new Exception ("Should never be reached");
}
- public static void Error_NamedArgument (NamedArgument na)
+ public static void Error_NamedArgument (NamedArgument na, Report Report)
{
Report.Error (1742, na.Name.Location, "An element access expression cannot use named argument");
}
Type t = ea.Expr.Type;
int rank = ea.Arguments.Count;
if (t.GetArrayRank () != rank) {
- Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
+ ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
ea.Arguments.Count.ToString (), t.GetArrayRank ().ToString ());
return null;
}
type = TypeManager.GetElementType (t);
if (type.IsPointer && !ec.IsUnsafe) {
- UnsafeError (ea.Location);
+ UnsafeError (ec, ea.Location);
}
foreach (Argument a in ea.Arguments) {
if (a is NamedArgument)
- ElementAccess.Error_NamedArgument ((NamedArgument) a);
+ ElementAccess.Error_NamedArgument ((NamedArgument) a, ec.Report);
a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
}
ig.Emit (OpCodes.Ldelem_Ref);
}
- protected override void Error_NegativeArrayIndex (Location loc)
+ protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
{
- Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
+ ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
}
/// <summary>
/// </summary>
static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
{
- //Console.WriteLine (new System.Diagnostics.StackTrace ());
has_type_arg = false; is_stobj = false;
t = TypeManager.TypeToCoreType (t);
if (TypeManager.IsEnumType (t))
instance_expr.CreateExpressionTree (ec),
new TypeOfMethod (get, loc));
- return CreateExpressionFactoryCall ("Call", args);
+ return CreateExpressionFactoryCall (ec, "Call", args);
}
protected virtual void CommonResolve (ResolveContext ec)
public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
{
if (right_side == EmptyExpression.OutAccess) {
- Report.Error (206, loc,
+ ec.Report.Error (206, loc,
"A property or indexer may not be passed as an out or ref parameter");
return null;
}
int additional = right_side == null ? 1 : 2;
Arguments args = new Arguments (arguments.Count + additional);
if (is_base_indexer) {
- Report.Error (1972, loc, "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
+ ec.Report.Error (1972, loc, "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
} else {
args.Add (new Argument (instance_expr));
}
Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type);
if (ilist.Methods == null) {
- Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
+ ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
TypeManager.CSharpName (indexer_type));
return null;
}
type = TypeManager.TypeToCoreType (pi.PropertyType);
if (type.IsPointer && !ec.IsUnsafe)
- UnsafeError (loc);
+ UnsafeError (ec, loc);
MethodInfo accessor;
if (right_side == null) {
} else {
accessor = set = pi.GetSetMethod (true);
if (accessor == null && pi.GetGetMethod (true) != null) {
- Report.SymbolRelatedToPreviousError (pi);
- Report.Error (200, loc, "The read only property or indexer `{0}' cannot be assigned to",
+ ec.Report.SymbolRelatedToPreviousError (pi);
+ ec.Report.Error (200, loc, "The read only property or indexer `{0}' cannot be assigned to",
TypeManager.GetFullNameSignature (pi));
return null;
}
}
if (accessor == null) {
- Report.SymbolRelatedToPreviousError (pi);
- Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks a `{1}' accessor",
+ ec.Report.SymbolRelatedToPreviousError (pi);
+ ec.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks a `{1}' accessor",
TypeManager.GetFullNameSignature (pi), GetAccessorName (right_side != null));
return null;
}
// Only base will allow this invocation to happen.
//
if (accessor.IsAbstract && this is BaseIndexerAccess) {
- Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (pi));
+ Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (pi));
}
bool must_do_cs1540_check;
if (set != null && get != null &&
(set.Attributes & MethodAttributes.MemberAccessMask) != (get.Attributes & MethodAttributes.MemberAccessMask)) {
- Report.SymbolRelatedToPreviousError (accessor);
- Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because a `{1}' accessor is inaccessible",
+ ec.Report.SymbolRelatedToPreviousError (accessor);
+ ec.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because a `{1}' accessor is inaccessible",
TypeManager.GetFullNameSignature (pi), GetAccessorName (right_side != null));
} else {
- Report.SymbolRelatedToPreviousError (pi);
- ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (pi));
+ ec.Report.SymbolRelatedToPreviousError (pi);
+ ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (pi), ec.Report);
}
}
if (!This.IsThisAvailable (ec)) {
if (ec.IsStatic) {
- Report.Error (1511, loc, "Keyword `base' is not available in a static method");
+ ec.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
} else {
- Report.Error (1512, loc, "Keyword `base' is not available in the current context");
+ ec.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
}
return null;
}
- member_lookup = MemberLookup (ec.CurrentType, null, base_type, Identifier,
+ member_lookup = MemberLookup (ec.Compiler, ec.CurrentType, null, base_type, Identifier,
AllMemberTypes, AllBindingFlags, loc);
if (member_lookup == null) {
- Error_MemberLookupFailed (ec.CurrentType, base_type, base_type, Identifier,
+ Error_MemberLookupFailed (ec, ec.CurrentType, base_type, base_type, Identifier,
null, AllMemberTypes, AllBindingFlags);
return null;
}
me.IsBase = true;
if (args != null) {
args.Resolve (ec);
- me.SetTypeArguments (args);
+ me.SetTypeArguments (ec, args);
}
return me;
public override Expression CreateExpressionTree (ResolveContext ec)
{
- MemberExpr.Error_BaseAccessInExpressionTree (loc);
+ MemberExpr.Error_BaseAccessInExpressionTree (ec, loc);
return base.CreateExpressionTree (ec);
}
}
args.Add (new Argument (source.CreateExpressionTree (ec)));
args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
args.Add (new Argument (new TypeOfMethod (method, loc)));
- return CreateExpressionFactoryCall ("Convert", args);
+ return CreateExpressionFactoryCall (ec, "Convert", args);
}
public override Expression DoResolve (ResolveContext ec)
{
ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
if (oa != null)
- AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
+ AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
eclass = ExprClass.Value;
return this;
if (dim.Length != 0 && dim [0] == '[') {
if (TypeManager.IsSpecialType (ltype)) {
- Report.Error (611, loc, "Array elements cannot be of type `{0}'", TypeManager.CSharpName (ltype));
+ ec.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", TypeManager.CSharpName (ltype));
return null;
}
if ((ltype.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
- Report.SymbolRelatedToPreviousError (ltype);
- Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
+ ec.Compiler.Report.SymbolRelatedToPreviousError (ltype);
+ ec.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
TypeManager.CSharpName (ltype));
}
}
throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
if (type.IsPointer && !ec.IsUnsafe){
- UnsafeError (loc);
+ UnsafeError (ec.Compiler.Report, loc);
}
eclass = ExprClass.Type;
public override Expression CreateExpressionTree (ResolveContext ec)
{
- Error_PointerInsideExpressionTree ();
+ Error_PointerInsideExpressionTree (ec);
return null;
}
Arguments args = new Arguments (2);
args.Add (new Argument (child.CreateExpressionTree (ec)));
args.Add (new Argument (new TypeOf (new TypeExpression (TypeManager.int32_type, loc), loc)));
- return CreateExpressionFactoryCall ("ConvertChecked", args);
+ return CreateExpressionFactoryCall (ec, "ConvertChecked", args);
}
public override void Emit (EmitContext ec)
Constant c = count as Constant;
if (c != null && c.IsNegative) {
- Report.Error (247, loc, "Cannot use a negative size with stackalloc");
+ ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
return null;
}
if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
- Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
+ ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
}
TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
args.Add (new Argument (((PropertyExpr)target).CreateSetterTypeOfExpression ()));
args.Add (new Argument (source.CreateExpressionTree (ec)));
- return CreateExpressionFactoryCall (
+ return CreateExpressionFactoryCall (ec,
source is CollectionOrObjectInitializers ? "ListBind" : "Bind",
args);
}
return expr;
}
- protected override Expression Error_MemberLookupFailed (Type type, MemberInfo[] members)
+ protected override Expression Error_MemberLookupFailed (ResolveContext ec, Type type, MemberInfo[] members)
{
MemberInfo member = members [0];
if (member.MemberType != MemberTypes.Property && member.MemberType != MemberTypes.Field)
- Report.Error (1913, loc, "Member `{0}' cannot be initialized. An object " +
+ ec.Report.Error (1913, loc, "Member `{0}' cannot be initialized. An object " +
"initializer may only be used for fields, or properties", TypeManager.GetFullNameSignature (member));
else
- Report.Error (1914, loc, " Static field or property `{0}' cannot be assigned in an object initializer",
+ ec.Report.Error (1914, loc, " Static field or property `{0}' cannot be assigned in an object initializer",
TypeManager.GetFullNameSignature (member));
return null;
{
}
- protected override void Error_TypeDoesNotContainDefinition (Type type, string name)
+ protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, Type type, string name)
{
if (TypeManager.HasElementType (type))
return;
- base.Error_TypeDoesNotContainDefinition (type, name);
+ base.Error_TypeDoesNotContainDefinition (ec, type, name);
}
}
expr_initializers.Add (a.CreateExpressionTree (ec));
args.Add (new Argument (new ArrayCreation (
- CreateExpressionTypeExpression (loc), "[]", expr_initializers, loc)));
- return CreateExpressionFactoryCall ("ElementInit", args);
+ CreateExpressionTypeExpression (ec, loc), "[]", expr_initializers, loc)));
+ return CreateExpressionFactoryCall (ec, "ElementInit", args);
}
protected override void CloneTo (CloneContext clonectx, Expression t)
throw new InternalErrorException ("This line should never be reached");
} else {
if (!TypeManager.ImplementsInterface (ec.CurrentInitializerVariable.Type, TypeManager.ienumerable_type)) {
- Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
+ ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
"object initializer because type `{1}' does not implement `{2}' interface",
ec.CurrentInitializerVariable.GetSignatureForError (),
TypeManager.CSharpName (ec.CurrentInitializerVariable.Type),
}
} else {
if (is_collection_initialization != (element_initializer == null)) {
- Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
+ ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
is_collection_initialization ? "collection initializer" : "object initializer");
continue;
}
if (!is_collection_initialization) {
if (element_names.Contains (element_initializer.Name)) {
- Report.Error (1912, element_initializer.Location,
+ ec.Report.Error (1912, element_initializer.Location,
"An object initializer includes more than one member `{0}' initialization",
element_initializer.Name);
} else {
type = ec.CurrentInitializerVariable.Type;
if (is_collection_initialization) {
if (TypeManager.HasElementType (type)) {
- Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
+ ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
TypeManager.CSharpName (type));
}
}
if (!initializers.IsEmpty)
args.Add (new Argument (initializers.CreateExpressionTree (ec)));
- return CreateExpressionFactoryCall (
+ return CreateExpressionFactoryCall (ec,
initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
args);
}
t.parameters.Add (atp.Clone (clonectx));
}
- AnonymousTypeClass CreateAnonymousType (ArrayList parameters)
+ AnonymousTypeClass CreateAnonymousType (ResolveContext ec, ArrayList parameters)
{
AnonymousTypeClass type = parent.Module.GetAnonymousType (parameters);
if (type != null)
return type;
- type = AnonymousTypeClass.Create (parent, parameters, loc);
+ type = AnonymousTypeClass.Create (ec.Compiler, parent, parameters, loc);
if (type == null)
return null;
type.DefineType ();
type.Define ();
type.EmitType ();
- if (Report.Errors == 0)
+ if (ec.Report.Errors == 0)
type.CloseType ();
parent.Module.AddAnonymousType (type);
AnonymousTypeClass anonymous_type;
if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
- Report.Error (836, loc, "Anonymous types cannot be used in this expression");
+ ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
return null;
}
if (parameters == null) {
- anonymous_type = CreateAnonymousType (EmptyParameters);
+ anonymous_type = CreateAnonymousType (ec, EmptyParameters);
return new New (new TypeExpression (anonymous_type.TypeBuilder, loc),
null, loc).Resolve (ec);
}
if (error)
return null;
- anonymous_type = CreateAnonymousType (parameters);
+ anonymous_type = CreateAnonymousType (ec, parameters);
if (anonymous_type == null)
return null;
return null;
if (e.eclass == ExprClass.MethodGroup) {
- Error_InvalidInitializer (e.ExprClassName);
+ Error_InvalidInitializer (ec, e.ExprClassName);
return null;
}
type = e.Type;
if (type == TypeManager.void_type || type == TypeManager.null_type ||
type == InternalType.AnonymousMethod || type.IsPointer) {
- Error_InvalidInitializer (e.GetSignatureForError ());
+ Error_InvalidInitializer (ec, e.GetSignatureForError ());
return null;
}
return e;
}
- protected virtual void Error_InvalidInitializer (string initializer)
+ protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
{
- Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",
+ ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",
Name, initializer);
}
return CurrentUsageVector.IsAssigned (vi, false) || CurrentUsageVector.IsFieldAssigned (vi, field_name);
}
+ protected static Report Report {
+ get { return RootContext.ToplevelTypes.Compiler.Report; }
+ }
+
public void SetAssigned (VariableInfo vi)
{
CurrentUsageVector.SetAssigned (vi);
return false;
}
- public static void Error_UnknownLabel (Location loc, string label)
+ public static void Error_UnknownLabel (Location loc, string label, Report Report)
{
Report.Error(159, loc, "The label `{0}:' could not be found within the scope of the goto statement",
label);
throw new InternalErrorException ("Shouldn't get here");
if (Parent == null) {
- Error_UnknownLabel (goto_stmt.loc, name);
+ Error_UnknownLabel (goto_stmt.loc, name, Report);
return false;
}
int errors = Report.Errors;
Parent.AddReturnOrigin (vector, exit_stmt);
if (errors == Report.Errors)
- exit_stmt.Error_FinallyClause ();
+ exit_stmt.Error_FinallyClause (Report);
} else {
saved_origins = new ReturnOrigin (saved_origins, vector, exit_stmt);
}
// A struct's constructor must always assign all fields.
// This method checks whether it actually does so.
// </summary>
- public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
+ public bool IsFullyInitialized (BlockContext ec, VariableInfo vi, Location loc)
{
if (struct_info == null)
return true;
bool ok = true;
+ FlowBranching branching = ec.CurrentBranching;
for (int i = 0; i < struct_info.Count; i++) {
FieldInfo field = struct_info.Fields [i];
if (!branching.IsFieldAssigned (vi, field.Name)) {
FieldBase fb = TypeManager.GetField (field);
if (fb is Property.BackingField) {
- Report.Error (843, loc,
+ ec.Report.Error (843, loc,
"An automatically implemented property `{0}' must be fully assigned before control leaves the constructor. Consider calling default contructor",
fb.GetSignatureForError ());
} else {
- Report.Error (171, loc,
+ ec.Report.Error (171, loc,
"Field `{0}' must be fully assigned before control leaves the constructor",
TypeManager.GetFullNameSignature (field));
}
if (sinfo [i] == null)
field_hash.Add (field.Name, ++Length);
else if (sinfo [i].InTransit) {
- Report.Error (523, String.Format (
+ RootContext.ToplevelTypes.Compiler.Report.Error (523, String.Format (
"Struct member `{0}.{1}' of type `{2}' causes " +
"a cycle in the structure layout",
type, field.Name, sinfo [i].Type));
if (IsAssigned (ec))
return true;
- Report.Error (165, loc,
+ ec.Report.Error (165, loc,
"Use of unassigned local variable `" + Name + "'");
ec.CurrentBranching.SetAssigned (this);
return false;
ec.CurrentBranching.IsFieldAssigned (this, name))
return true;
- Report.Error (170, loc,
+ ec.Report.Error (170, loc,
"Use of possibly unassigned field `" + name + "'");
ec.CurrentBranching.SetFieldAssigned (this, name);
return false;
get { throw new NotImplementedException (); }
}
- public void VerifyClsCompliance ()
+ public void VerifyClsCompliance (Report r)
{
}
}
throw new NotImplementedException ();
}
- public bool FixAllTypes ()
+ public bool FixAllTypes (ResolveContext ec)
{
return false;
}
/// Resolve the constraints - but only resolve things into Expression's, not
/// into actual types.
/// </summary>
- public bool Resolve (MemberCore ec, TypeParameter tp)
+ public bool Resolve (MemberCore ec, TypeParameter tp, Report Report)
{
if (resolved)
return true;
if (errors != Report.Errors)
return false;
- NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
+ NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError (), Report);
return false;
}
return true;
}
- bool CheckTypeParameterConstraints (Type tparam, ref TypeExpr prevConstraint, ArrayList seen)
+ bool CheckTypeParameterConstraints (Type tparam, ref TypeExpr prevConstraint, ArrayList seen, Report Report)
{
seen.Add (tparam);
return false;
}
- if (!CheckTypeParameterConstraints (expr.Type, ref prevConstraint, seen))
+ if (!CheckTypeParameterConstraints (expr.Type, ref prevConstraint, seen, Report))
return false;
}
/// <summary>
/// Resolve the constraints into actual types.
/// </summary>
- public bool ResolveTypes (IMemberContext ec)
+ public bool ResolveTypes (IMemberContext ec, Report r)
{
if (resolved_types)
return true;
ArrayList seen = new ArrayList ();
TypeExpr prev_constraint = class_constraint;
foreach (TypeExpr expr in type_param_constraints) {
- if (!CheckTypeParameterConstraints (expr.Type, ref prev_constraint, seen))
+ if (!CheckTypeParameterConstraints (expr.Type, ref prev_constraint, seen, r))
return false;
seen.Clear ();
}
return true;
}
- public void VerifyClsCompliance ()
+ public void VerifyClsCompliance (Report r)
{
if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
- Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
+ Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location, r);
if (iface_constraint_types != null) {
for (int i = 0; i < iface_constraint_types.Length; ++i) {
if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
- ((TypeExpr)iface_constraints [i]).Location);
+ ((TypeExpr)iface_constraints [i]).Location, r);
}
}
}
- void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
+ void Warning_ConstrainIsNotClsCompliant (Type t, Location loc, Report Report)
{
Report.SymbolRelatedToPreviousError (t);
Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
public bool Resolve (DeclSpace ds)
{
if (constraints != null) {
- if (!constraints.Resolve (ds, this)) {
+ if (!constraints.Resolve (ds, this, Report)) {
constraints = null;
return false;
}
public bool ResolveType (IMemberContext ec)
{
if (constraints != null) {
- if (!constraints.ResolveTypes (ec)) {
+ if (!constraints.ResolveTypes (ec, Report)) {
constraints = null;
return false;
}
if (new_constraints == null)
return true;
- if (!new_constraints.Resolve (ec, this))
+ if (!new_constraints.Resolve (ec, this, Report))
return false;
- if (!new_constraints.ResolveTypes (ec))
+ if (!new_constraints.ResolveTypes (ec, Report))
return false;
if (constraints != null)
atypes[i] = te.Type;
if (te.Type.IsSealed && te.Type.IsAbstract) {
- Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
+ ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
te.GetSignatureForError ());
ok = false;
}
if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
- Report.Error (306, te.Location,
+ ec.Compiler.Report.Error (306, te.Location,
"The type `{0}' may not be used as a type argument",
te.GetSignatureForError ());
ok = false;
protected readonly Type[] gen_params;
protected readonly Type[] atypes;
protected readonly Location loc;
+ protected Report Report;
- protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
+ protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc, Report r)
{
this.gen_params = gen_params;
this.atypes = atypes;
this.loc = loc;
+ this.Report = r;
}
/// <summary>
// when resolving base type of unresolved generic type
// with constraints. We are waiting with CheckConsttraints
// after type-definition but not in this case
- if (!((Constraints) agc).Resolve (null, null))
+ if (!((Constraints) agc).Resolve (null, null, Report))
return true;
}
is_class = agc.IsReferenceType;
{
MethodConstraintChecker checker = new MethodConstraintChecker (
definition, definition.GetGenericArguments (),
- instantiated.GetGenericArguments (), loc);
+ instantiated.GetGenericArguments (), loc, ec.Compiler.Report);
return checker.CheckConstraints (ec);
}
Type[] atypes, Location loc)
{
TypeConstraintChecker checker = new TypeConstraintChecker (
- gt, gen_params, atypes, loc);
+ gt, gen_params, atypes, loc, ec.Compiler.Report);
return checker.CheckConstraints (ec);
}
MethodBase definition;
public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
- Type[] atypes, Location loc)
- : base (gen_params, atypes, loc)
+ Type[] atypes, Location loc, Report r)
+ : base (gen_params, atypes, loc, r)
{
this.definition = definition;
}
Type gt;
public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
- Location loc)
- : base (gen_params, atypes, loc)
+ Location loc, Report r)
+ : base (gen_params, atypes, loc, r)
{
this.gt = gt;
}
if (b == null)
b = new Block (null);
- b.Error_AlreadyDeclaredTypeParameter (parameters [i].Location,
+ b.Error_AlreadyDeclaredTypeParameter (Report, parameters [i].Location,
type_argument_name, "method parameter");
}
if (tp.Constraints == null)
continue;
- tp.Constraints.VerifyClsCompliance ();
+ tp.Constraints.VerifyClsCompliance (Report);
}
}
}
return 0;
}
- /// <summary>
- /// Type inference.
- /// </summary>
- public static bool InferTypeArguments (AParametersCollection param, ref MethodBase method)
+/*
+ public static bool InferTypeArguments (ResolveContext ec, AParametersCollection param, ref MethodBase method)
{
if (!TypeManager.IsGenericMethod (method))
return true;
ATypeInference ti = ATypeInference.CreateInstance (DelegateCreation.CreateDelegateMethodArguments (param, Location.Null));
- Type[] i_args = ti.InferDelegateArguments (method);
+ Type[] i_args = ti.InferDelegateArguments (ec, method);
if (i_args == null)
return false;
method = ((MethodInfo) method).MakeGenericMethod (i_args);
return true;
}
+*/
}
abstract class ATypeInference
}
public abstract Type[] InferMethodArguments (ResolveContext ec, MethodBase method);
- public abstract Type[] InferDelegateArguments (MethodBase method);
+// public abstract Type[] InferDelegateArguments (ResolveContext ec, MethodBase method);
}
//
}
}
- public override Type[] InferDelegateArguments (MethodBase method)
+/*
+ public override Type[] InferDelegateArguments (ResolveContext ec, MethodBase method)
{
AParametersCollection pd = TypeManager.GetParameterData (method);
if (arg_count != pd.Count)
context.LowerBoundInference (arguments [i].Expr.Type, t);
}
- if (!context.FixAllTypes ())
+ if (!context.FixAllTypes (ec))
return null;
return context.InferredTypeArguments;
}
-
+*/
public override Type[] InferMethodArguments (ResolveContext ec, MethodBase method)
{
Type[] method_generic_args = method.GetGenericArguments ();
//
AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
if (am != null) {
- if (am.ExplicitTypeInference (tic, method_parameter))
+ if (am.ExplicitTypeInference (ec, tic, method_parameter))
--score;
continue;
}
// we don't need to call it in cycle
//
bool fixed_any = false;
- if (!tic.FixIndependentTypeArguments (ptypes, ref fixed_any))
+ if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
return false;
return DoSecondPhase (ec, tic, ptypes, !fixed_any);
bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, Type[] methodParameters, bool fixDependent)
{
bool fixed_any = false;
- if (fixDependent && !tic.FixDependentTypes (ref fixed_any))
+ if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
return false;
// If no further unfixed type variables exist, type inference succeeds
t_i = t_i.GetGenericArguments () [0];
}
- MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
+ MethodInfo mi = Delegate.GetInvokeMethod (ec.Compiler, t_i, t_i);
Type rtype = mi.ReturnType;
#if MS_COMPATIBLE
rtype = g_args[rtype.GenericParameterPosition];
#endif
- if (tic.IsReturnTypeNonDependent (mi, rtype))
+ if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
}
return 1;
}
- public bool FixAllTypes ()
+ public bool FixAllTypes (ResolveContext ec)
{
for (int i = 0; i < unfixed_types.Length; ++i) {
- if (!FixType (i))
+ if (!FixType (ec, i))
return false;
}
return true;
// a, There is at least one type variable Xj that depends on Xi
// b, Xi has a non-empty set of bounds
//
- public bool FixDependentTypes (ref bool fixed_any)
+ public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
{
for (int i = 0; i < unfixed_types.Length; ++i) {
if (unfixed_types[i] == null)
if (bounds[i] == null)
continue;
- if (!FixType (i))
+ if (!FixType (ec, i))
return false;
fixed_any = true;
//
// All unfixed type variables Xi which depend on no Xj are fixed
//
- public bool FixIndependentTypeArguments (Type[] methodParameters, ref bool fixed_any)
+ public bool FixIndependentTypeArguments (ResolveContext ec, Type[] methodParameters, ref bool fixed_any)
{
ArrayList types_to_fix = new ArrayList (unfixed_types);
for (int i = 0; i < methodParameters.Length; ++i) {
if (t.IsGenericParameter)
continue;
- MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
+ MethodInfo invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
Type rtype = invoke.ReturnType;
if (!rtype.IsGenericParameter && !rtype.IsGenericType)
continue;
continue;
int idx = IsUnfixed (t);
- if (idx >= 0 && !FixType (idx)) {
+ if (idx >= 0 && !FixType (ec, idx)) {
return false;
}
}
//
// 26.3.3.10 Fixing
//
- public bool FixType (int i)
+ public bool FixType (ResolveContext ec, int i)
{
// It's already fixed
if (unfixed_types[i] == null)
if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
if (cbound.Kind != BoundKind.Exact) {
- if (!Convert.ImplicitConversionExists (null, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
+ if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
break;
}
}
if (bound.Kind != BoundKind.Exact) {
- if (!Convert.ImplicitConversionExists (null, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
+ if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
break;
}
}
if (bound.Kind == BoundKind.Lower) {
- if (!Convert.ImplicitConversionExists (null, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
+ if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
break;
}
} else {
- if (!Convert.ImplicitConversionExists (null, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
+ if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
break;
}
}
// Tests whether all delegate input arguments are fixed and generic output type
// requires output type inference
//
- public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
+ public bool IsReturnTypeNonDependent (ResolveContext ec, MethodInfo invoke, Type returnType)
{
if (returnType.IsGenericParameter) {
if (IsFixed (returnType))
return false;
} else if (returnType.IsGenericType) {
if (TypeManager.IsDelegateType (returnType)) {
- invoke = Delegate.GetInvokeMethod (returnType, returnType);
- return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
+ invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType, returnType);
+ return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
}
Type[] g_args = returnType.GetGenericArguments ();
AnonymousMethodExpression ame = e as AnonymousMethodExpression;
if (ame != null) {
Type rt = ame.InferReturnType (ec, this, t);
- MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
+ MethodInfo invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
if (rt == null) {
AParametersCollection pd = TypeManager.GetParameterData (invoke);
if (!TypeManager.IsDelegateType (t))
return 0;
- MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
+ MethodInfo invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
Type rtype = invoke.ReturnType;
#if MS_COMPATIBLE
// Blablabla, because reflection does not work with dynamic types
// inside an unsafe class. See test-martin-29.cs for an example.
//
if (!ec.CurrentAnonymousMethod.IsIterator) {
- Report.Error (1621, loc,
+ ec.Report.Error (1621, loc,
"The yield statement cannot be used inside " +
"anonymous method blocks");
return false;
loc = l;
}
- public override void Error_FinallyClause ()
+ public override void Error_FinallyClause (Report Report)
{
Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
}
{
this.host = host;
- Block = new ToplevelBlock (host.Iterator.Container.Toplevel, ParametersCompiled.EmptyReadOnlyParameters, Location);
+ Block = new ToplevelBlock (Compiler, host.Iterator.Container.Toplevel, ParametersCompiled.EmptyReadOnlyParameters, Location);
}
public override EmitContext CreateEmitContext (ILGenerator ig)
new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
if (TypeManager.int_interlocked_compare_exchange == null) {
- Type t = TypeManager.CoreLookupType ("System.Threading", "Interlocked", Kind.Class, true);
+ Type t = TypeManager.CoreLookupType (ec.Compiler, "System.Threading", "Interlocked", Kind.Class, true);
if (t != null) {
TypeManager.int_interlocked_compare_exchange = TypeManager.GetPredefinedMethod (
t, "CompareExchange", loc, TypeManager.int32_type,
{
host.AddMethod (this);
- Block = new ToplevelBlock (host.Iterator.Container, ParametersCompiled.EmptyReadOnlyParameters, Location);
+ Block = new ToplevelBlock (Compiler, host.Iterator.Container, ParametersCompiled.EmptyReadOnlyParameters, Location);
Block.AddStatement (new DisposeMethodStatement (host.Iterator));
}
}
name = new MemberName (name, "Current", Location);
- ToplevelBlock get_block = new ToplevelBlock (Location);
+ ToplevelBlock get_block = new ToplevelBlock (Compiler, Location);
get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
Accessor getter = new Accessor (get_block, 0, null, null, Location);
ParametersCompiled.EmptyReadOnlyParameters, null);
AddMethod (reset);
- reset.Block = new ToplevelBlock (Location);
+ reset.Block = new ToplevelBlock (Compiler, Location);
- Type ex_type = TypeManager.CoreLookupType ("System", "NotSupportedException", Kind.Class, true);
+ Type ex_type = TypeManager.CoreLookupType (Compiler, "System", "NotSupportedException", Kind.Class, true);
if (ex_type == null)
return;
//
// Our constructor
//
- private Iterator (IMethodData method, TypeContainer host, Type iterator_type, bool is_enumerable)
+ private Iterator (CompilerContext ctx, IMethodData method, TypeContainer host, Type iterator_type, bool is_enumerable)
: base (
- new ToplevelBlock (method.Block, ParametersCompiled.EmptyReadOnlyParameters, method.Block.StartLocation),
+ new ToplevelBlock (ctx, method.Block, ParametersCompiled.EmptyReadOnlyParameters, method.Block.StartLocation),
TypeManager.bool_type,
method.Location)
{
throw new NotSupportedException ("ET");
}
- public static void CreateIterator (IMethodData method, TypeContainer parent, int modifiers)
+ public static void CreateIterator (IMethodData method, TypeContainer parent, int modifiers, CompilerContext ctx)
{
bool is_enumerable;
Type iterator_type;
return;
if (!CheckType (ret, out iterator_type, out is_enumerable)) {
- Report.Error (1624, method.Location,
+ ctx.Report.Error (1624, method.Location,
"The body of `{0}' cannot be an iterator block " +
"because `{1}' is not an iterator interface type",
method.GetSignatureForError (),
Parameter p = parameters [i];
Parameter.Modifier mod = p.ModFlags;
if ((mod & Parameter.Modifier.ISBYREF) != 0) {
- Report.Error (1623, p.Location,
+ ctx.Report.Error (1623, p.Location,
"Iterators cannot have ref or out parameters");
return;
}
if (p is ArglistParameter) {
- Report.Error (1636, method.Location,
+ ctx.Report.Error (1636, method.Location,
"__arglist is not allowed in parameter list of iterators");
return;
}
if (parameters.Types [i].IsPointer) {
- Report.Error (1637, p.Location,
+ ctx.Report.Error (1637, p.Location,
"Iterators cannot have unsafe parameters or " +
"yield types");
return;
}
if ((modifiers & Modifiers.UNSAFE) != 0) {
- Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
+ ctx.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
return;
}
- Iterator iter = new Iterator (method, parent, iterator_type, is_enumerable);
+ Iterator iter = new Iterator (ctx, method, parent, iterator_type, is_enumerable);
iter.Storey.DefineType ();
}
Arguments arguments = new Arguments (2);
arguments.Add (new Argument (expr));
arguments.Add (new Argument (args));
- return CreateExpressionFactoryCall ("Lambda",
+ return CreateExpressionFactoryCall (ec, "Lambda",
new TypeArguments (new TypeExpression (delegate_type, loc)),
arguments);
}
if (!TypeManager.IsDelegateType (delegateType))
return null;
- AParametersCollection d_params = TypeManager.GetDelegateParameters (delegateType);
+ AParametersCollection d_params = TypeManager.GetDelegateParameters (ec, delegateType);
if (HasExplicitParameters) {
- if (!VerifyExplicitParameters (delegateType, d_params, ec.IsInProbingMode))
+ if (!VerifyExplicitParameters (ec, delegateType, d_params))
return null;
return Parameters;
// If L has an implicitly typed parameter list we make implicit parameters explicit
// Set each parameter of L is given the type of the corresponding parameter in D
//
- if (!VerifyParameterCompatibility (delegateType, d_params, ec.IsInProbingMode))
+ if (!VerifyParameterCompatibility (ec, delegateType, d_params, ec.IsInProbingMode))
return null;
Type [] ptypes = new Type [Parameters.Count];
Arguments arguments = new Arguments (2);
arguments.Add (new Argument (expr));
arguments.Add (new Argument (args));
- return CreateExpressionFactoryCall ("Lambda",
+ return CreateExpressionFactoryCall (ec, "Lambda",
new TypeArguments (new TypeExpression (type, loc)),
arguments);
}
statement = Expr as ExpressionStatement;
if (statement == null)
- Expr.Error_InvalidExpressionStatement ();
+ Expr.Error_InvalidExpressionStatement (ec);
return true;
}
{
}
- protected override Expression Error_MemberLookupFailed (Type container_type, Type qualifier_type,
+ protected override Expression Error_MemberLookupFailed (ResolveContext ec, Type container_type, Type qualifier_type,
Type queried_type, string name, string class_name, MemberTypes mt, BindingFlags bf)
{
- Report.Error (1935, loc, "An implementation of `{0}' query expression pattern could not be found. " +
+ ec.Report.Error (1935, loc, "An implementation of `{0}' query expression pattern could not be found. " +
"Are you missing `System.Linq' using directive or `System.Core.dll' assembly reference?",
name);
return null;
return rmg;
}
- public bool AmbiguousCall (MethodBase ambiguous)
+ public bool AmbiguousCall (ResolveContext ec, MethodBase ambiguous)
{
- Report.SymbolRelatedToPreviousError ((MethodInfo) mg);
- Report.SymbolRelatedToPreviousError (ambiguous);
- Report.Error (1940, loc, "Ambiguous implementation of the query pattern `{0}' for source type `{1}'",
+ ec.Report.SymbolRelatedToPreviousError ((MethodInfo) mg);
+ ec.Report.SymbolRelatedToPreviousError (ambiguous);
+ ec.Report.Error (1940, loc, "Ambiguous implementation of the query pattern `{0}' for source type `{1}'",
mg.Name, mg.InstanceExpression.GetSignatureForError ());
return true;
}
#if GMCS_SOURCE
TypeInferenceContext tic = new TypeInferenceContext (TypeManager.GetTypeArguments (source_type));
tic.OutputTypeInference (ec, a.Expr, source_type);
- if (tic.FixAllTypes ()) {
+ if (tic.FixAllTypes (ec)) {
source_type = TypeManager.DropGenericTypeArguments (source_type).MakeGenericType (tic.InferredTypeArguments);
}
#else
}
if (!Convert.ImplicitConversionExists (ec, a.Expr, source_type)) {
- Report.Error (1936, loc, "An implementation of `{0}' query expression pattern for source type `{1}' could not be found",
+ ec.Report.Error (1936, loc, "An implementation of `{0}' query expression pattern for source type `{1}' could not be found",
mg.Name, TypeManager.CSharpName (a.Type));
return true;
}
return false;
if (mg.Name == "SelectMany") {
- Report.Error (1943, loc,
+ ec.Report.Error (1943, loc,
"An expression type is incorrect in a subsequent `from' clause in a query expression with source type `{0}'",
arguments [0].GetSignatureForError ());
} else {
- Report.Error (1942, loc,
+ ec.Report.Error (1942, loc,
"An expression type in `{0}' clause is incorrect. Type inference failed in the call to `{1}'",
mg.Name.ToLower (), mg.Name);
}
{
}
- protected override void Error_InvalidInitializer (string initializer)
+ protected override void Error_InvalidInitializer (ResolveContext ec, string initializer)
{
- Report.Error (1932, loc, "A range variable `{0}' cannot be initialized with `{1}'",
+ ec.Report.Error (1932, loc, "A range variable `{0}' cannot be initialized with `{1}'",
Name, initializer);
}
}
}
LambdaExpression result_selector = new LambdaExpression (lt.Location);
- result_selector.Block = new QueryBlock (block.Parent, block.Parameters, into_variable, block.StartLocation);
+ result_selector.Block = new QueryBlock (ec.Compiler, block.Parent, block.Parameters, into_variable, block.StartLocation);
result_selector.Block.AddStatement (new ContextualReturn (result_selector_expr));
args.Add (new Argument (result_selector));
}
LambdaExpression result_selector = new LambdaExpression (lt.Location);
- result_selector.Block = new QueryBlock (block.Parent, block.Parameters, lt, block.StartLocation);
+ result_selector.Block = new QueryBlock (ec.Compiler, block.Parent, block.Parameters, lt, block.StartLocation);
result_selector.Block.AddStatement (new ContextualReturn (result_selector_expr));
args.Add (new Argument (result_selector));
}
}
- public QueryBlock (Block parent, LocatedToken lt, Location start)
- : base (parent, new ParametersCompiled (new ImplicitQueryParameter (lt.Value, lt.Location)), start)
+ public QueryBlock (CompilerContext ctx, Block parent, LocatedToken lt, Location start)
+ : base (ctx, parent, new ParametersCompiled (new ImplicitQueryParameter (lt.Value, lt.Location)), start)
{
if (parent != null)
base.CheckParentConflictName (parent.Toplevel, lt.Value, lt.Location);
}
- public QueryBlock (Block parent, ParametersCompiled parameters, LocatedToken lt, Location start)
- : base (parent, new ParametersCompiled (parameters [0].Clone (), new ImplicitQueryParameter (lt.Value, lt.Location)), start)
+ public QueryBlock (CompilerContext ctx, Block parent, ParametersCompiled parameters, LocatedToken lt, Location start)
+ : base (ctx, parent, new ParametersCompiled (parameters [0].Clone (), new ImplicitQueryParameter (lt.Value, lt.Location)), start)
{
}
- public QueryBlock (Block parent, Location start)
- : base (parent, parent.Toplevel.Parameters.Clone (), start)
+ public QueryBlock (CompilerContext ctx, Block parent, Location start)
+ : base (ctx, parent, parent.Toplevel.Parameters.Clone (), start)
{
}
var);
}
- public override void Error_AlreadyDeclaredTypeParameter (Location loc, string name, string conflict)
+ public override void Error_AlreadyDeclaredTypeParameter (Report r, Location loc, string name, string conflict)
{
- Report.Error (1948, loc, "A range variable `{0}' conflicts with a method type parameter",
+ r.Error (1948, loc, "A range variable `{0}' conflicts with a method type parameter",
name);
}
}
public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type t, bool expl)
{
if (TypeManager.IsGenericParameter (t)) {
- Report.Error(403, loc,
+ ec.Report.Error(403, loc,
"Cannot convert null to the type parameter `{0}' because it could be a value " +
"type. Consider using `default ({0})' instead", t.Name);
return;
}
if (TypeManager.IsValueType (t)) {
- Report.Error(37, loc, "Cannot convert null to `{0}' because it is a value type",
+ ec.Report.Error(37, loc, "Cannot convert null to `{0}' because it is a value type",
TypeManager.CSharpName(t));
return;
}
public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type target, bool expl)
{
if (target == TypeManager.float_type) {
- Error_664 (loc, "float", "f");
+ Error_664 (ec, loc, "float", "f");
return;
}
if (target == TypeManager.decimal_type) {
- Error_664 (loc, "decimal", "m");
+ Error_664 (ec, loc, "decimal", "m");
return;
}
base.Error_ValueCannotBeConverted (ec, loc, target, expl);
}
- static void Error_664 (Location loc, string type, string suffix)
+ static void Error_664 (ResolveContext ec, Location loc, string type, string suffix)
{
- Report.Error (664, loc,
+ ec.Report.Error (664, loc,
"Literal of type double cannot be implicitly converted to type `{0}'. Add suffix `{1}' to create a literal of this type",
type, suffix);
}
// <summary>
// This must be called before parsing/tokenizing any files.
// </summary>
- static public void AddFile (string name)
+ static public void AddFile (Report r, string name)
{
string path = Path.GetFullPath (name);
int id = (int) source_files [path];
string other_name = ((SourceFile) source_list [id - 1]).Name;
if (name.Equals (other_name))
- Report.Warning (2002, 1, "Source file `{0}' specified multiple times", other_name);
+ r.Warning (2002, 1, "Source file `{0}' specified multiple times", other_name);
else
- Report.Warning (2002, 1, "Source filenames `{0}' and `{1}' both refer to the same file: {2}", name, other_name, path);
+ r.Warning (2002, 1, "Source filenames `{0}' and `{1}' both refer to the same file: {2}", name, other_name, path);
return;
}
// Returns the new mask. Side effect: reports any
// incorrect attributes.
// </summary>
- public static int Check (int allowed, int mod, int def_access, Location l)
+ public static int Check (int allowed, int mod, int def_access, Location l, Report Report)
{
int invalid_flags = (~allowed) & (mod & (Modifiers.TOP - 1));
int i;
int a = mod;
if ((mod & Modifiers.UNSAFE) != 0){
- RootContext.CheckUnsafeOption (l);
+ RootContext.CheckUnsafeOption (l, Report);
}
//
a = ((a & 2) >> 1) + (a & 5);
a = ((a & 4) >> 2) + (a & 3);
if (a > 1)
- Report.Error (107, l, "More than one protection modifier specified");
+ Report.Error (107, l, "More than one protection modifier specified", Report);
return mod;
}
if ((i & invalid_flags) == 0)
continue;
- Error_InvalidModifier (l, Name (i));
+ Error_InvalidModifier (l, Name (i), Report);
}
return allowed & mod;
}
- public static void Error_InvalidModifier (Location l, string name)
+ public static void Error_InvalidModifier (Location l, string name, Report Report)
{
- Report.Error (106, l, "The modifier `" + name + "' is not valid for this item");
+ Report.Error (106, l, "The modifier `" + name + "' is not valid for this item", Report);
}
}
}
referenced_assemblies = n;
}
- public void ComputeNamespace (Type extensionType)
+ public void ComputeNamespace (CompilerContext ctx, Type extensionType)
{
foreach (Assembly a in referenced_assemblies) {
try {
ComputeNamespaces (a, extensionType);
} catch (TypeLoadException e) {
- Report.Error (11, Location.Null, e.Message);
+ ctx.Report.Error (11, Location.Null, e.Message);
} catch (System.IO.FileNotFoundException) {
- Report.Error (12, Location.Null, "An assembly `{0}' is used without being referenced",
+ ctx.Report.Error (12, Location.Null, "An assembly `{0}' is used without being referenced",
a.FullName);
}
}
}
- public virtual Type LookupTypeReflection (string name, Location loc, bool must_be_unique)
+ public virtual Type LookupTypeReflection (CompilerContext ctx, string name, Location loc, bool must_be_unique)
{
Type found_type = null;
if (t.Assembly == found_type.Assembly)
continue;
- Report.SymbolRelatedToPreviousError (found_type);
- Report.SymbolRelatedToPreviousError (t);
+ ctx.Report.SymbolRelatedToPreviousError (found_type);
+ ctx.Report.SymbolRelatedToPreviousError (t);
if (loc.IsNull) {
- Error_AmbiguousPredefinedType (loc, name, found_type);
+ Error_AmbiguousPredefinedType (ctx, loc, name, found_type);
} else {
- Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
+ ctx.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
}
return found_type;
return result == null ? result : result.Keys;
}
- protected void Error_AmbiguousPredefinedType (Location loc, string name, Type type)
+ protected static void Error_AmbiguousPredefinedType (CompilerContext ctx, Location loc, string name, Type type)
{
- Report.Warning (1685, 1, loc,
+ ctx.Report.Warning (1685, 1, loc,
"The predefined type `{0}' is ambiguous. Using definition from `{1}'",
name, type.Assembly.FullName);
}
RegisterNamespace (t.Namespace);
}
- public void ComputeNamespaces ()
+ public void ComputeNamespaces (CompilerContext ctx)
{
//
// Do very early lookup because type is required when we cache
// imported extension types in ComputeNamespaces
//
- Type extension_attribute_type = TypeManager.CoreLookupType ("System.Runtime.CompilerServices", "ExtensionAttribute", Kind.Class, false);
+ Type extension_attribute_type = TypeManager.CoreLookupType (ctx, "System.Runtime.CompilerServices", "ExtensionAttribute", Kind.Class, false);
foreach (RootNamespace rn in root_namespaces.Values) {
- rn.ComputeNamespace (extension_attribute_type);
+ rn.ComputeNamespace (ctx, extension_attribute_type);
}
}
- public void DefineRootNamespace (string alias, Assembly assembly)
+ public void DefineRootNamespace (string alias, Assembly assembly, CompilerContext ctx)
{
if (alias == alias_name) {
- NamespaceEntry.Error_GlobalNamespaceRedefined (Location.Null);
+ NamespaceEntry.Error_GlobalNamespaceRedefined (Location.Null, ctx.Report);
return;
}
retval.AddAssemblyReference (assembly);
}
- public override void Error_NamespaceDoesNotExist (Location loc, string name)
+ public override void Error_NamespaceDoesNotExist (Location loc, string name, Report Report)
{
Report.Error (400, loc, "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
name);
return (RootNamespace) root_namespaces[name];
}
- public override Type LookupTypeReflection (string name, Location loc, bool must_be_unique)
+ public override Type LookupTypeReflection (CompilerContext ctx, string name, Location loc, bool must_be_unique)
{
- Type found_type = base.LookupTypeReflection (name, loc, must_be_unique);
+ Type found_type = base.LookupTypeReflection (ctx, name, loc, must_be_unique);
if (modules != null) {
foreach (Module module in modules) {
continue;
}
- Report.SymbolRelatedToPreviousError (found_type);
+ ctx.Report.SymbolRelatedToPreviousError (found_type);
if (loc.IsNull) {
DeclSpace ds = TypeManager.LookupDeclSpace (t);
- Error_AmbiguousPredefinedType (ds.Location, name, found_type);
+ Error_AmbiguousPredefinedType (ctx, ds.Location, name, found_type);
return found_type;
}
- Report.SymbolRelatedToPreviousError (t);
- Report.Warning (436, 2, loc, "The type `{0}' conflicts with the imported type `{1}'. Ignoring the imported type definition",
+ ctx.Report.SymbolRelatedToPreviousError (t);
+ ctx.Report.Warning (436, 2, loc, "The type `{0}' conflicts with the imported type `{1}'. Ignoring the imported type definition",
TypeManager.CSharpName (t), TypeManager.CSharpName (found_type));
return t;
}
return this;
}
- public virtual void Error_NamespaceDoesNotExist (Location loc, string name)
+ public virtual void Error_NamespaceDoesNotExist (Location loc, string name, Report Report)
{
if (name.IndexOf ('`') > 0) {
- FullNamedExpression retval = Lookup (SimpleName.RemoveGenericArity (name), loc);
+ FullNamedExpression retval = Lookup (RootContext.ToplevelTypes.Compiler, SimpleName.RemoveGenericArity (name), loc);
if (retval != null) {
Error_TypeArgumentsCannotBeUsed (retval, loc);
return;
public static void Error_InvalidNumberOfTypeArguments (Type t, Location loc)
{
- Report.SymbolRelatedToPreviousError (t);
- Report.Error (305, loc, "Using the generic type `{0}' requires `{1}' type argument(s)",
+ RootContext.ToplevelTypes.Compiler.Report.SymbolRelatedToPreviousError (t);
+ RootContext.ToplevelTypes.Compiler.Report.Error (305, loc, "Using the generic type `{0}' requires `{1}' type argument(s)",
TypeManager.CSharpName(t), TypeManager.GetNumberOfTypeArguments(t).ToString());
}
public static void Error_TypeArgumentsCannotBeUsed (FullNamedExpression expr, Location loc)
{
if (expr is TypeExpr) {
- Report.SymbolRelatedToPreviousError (expr.Type);
+ RootContext.ToplevelTypes.Compiler.Report.SymbolRelatedToPreviousError (expr.Type);
Error_TypeArgumentsCannotBeUsed (loc, "type", expr.GetSignatureForError ());
} else {
- expr.Error_ExpressionCannotBeGeneric (loc);
+ RootContext.ToplevelTypes.Compiler.Report.Error (307, loc, "The {0} `{1}' cannot be used with type arguments",
+ expr.ExprClassName, expr.GetSignatureForError ());
}
}
public static void Error_TypeArgumentsCannotBeUsed (MethodBase mi, Location loc)
{
- Report.SymbolRelatedToPreviousError (mi);
+ RootContext.ToplevelTypes.Compiler.Report.SymbolRelatedToPreviousError (mi);
Error_TypeArgumentsCannotBeUsed (loc, "method", TypeManager.CSharpSignature (mi));
}
static void Error_TypeArgumentsCannotBeUsed (Location loc, string type, string name)
{
- Report.Error(308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
+ RootContext.ToplevelTypes.Compiler.Report.Error(308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
type, name);
}
return declspaces != null && declspaces [name] != null;
}
- TypeExpr LookupType (string name, Location loc)
+ TypeExpr LookupType (CompilerContext ctx, string name, Location loc)
{
if (cached_types.Contains (name))
return cached_types [name] as TypeExpr;
}
}
string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
- Type rt = root.LookupTypeReflection (lookup, loc, t == null);
+ Type rt = root.LookupTypeReflection (ctx, lookup, loc, t == null);
// HACK: loc.IsNull when the type is core type
if (t == null || (rt != null && loc.IsNull))
return null;
}
- public FullNamedExpression Lookup (string name, Location loc)
+ public FullNamedExpression Lookup (CompilerContext ctx, string name, Location loc)
{
if (namespaces.Contains (name))
return (Namespace) namespaces [name];
- return LookupType (name, loc);
+ return LookupType (ctx, name, loc);
}
//
resolved = fne as Namespace;
if (resolved == null) {
- Report.SymbolRelatedToPreviousError (fne.Type);
- Report.Error (138, Location,
+ rc.Compiler.Report.SymbolRelatedToPreviousError (fne.Type);
+ rc.Compiler.Report.Error (138, Location,
"`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
GetSignatureForError ());
}
{
FullNamedExpression fne = GlobalRootNamespace.Instance.GetRootNamespace (Alias);
if (fne == null) {
- Report.Error (430, Location,
+ rc.Compiler.Report.Error (430, Location,
"The extern alias `{0}' was not specified in -reference option",
Alias);
}
public void AddUsing (MemberName name, Location loc)
{
if (DeclarationFound){
- Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
+ Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
}
if (using_clauses == null) {
} else {
foreach (UsingEntry old_entry in using_clauses) {
if (name.Equals (old_entry.MemberName)) {
- Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
- Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
+ Compiler.Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
+ Compiler.Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
return;
}
}
{
// TODO: This is parser bussines
if (DeclarationFound){
- Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
+ Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
}
if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
- Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
+ Compiler.Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
" the global namespace will be used instead");
AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
}
- public void AddUsingExternalAlias (string alias, Location loc)
+ public void AddUsingExternalAlias (string alias, Location loc, Report Report)
{
// TODO: Do this in parser
bool not_first = using_clauses != null || DeclarationFound;
Report.Error (439, loc, "An extern alias declaration must precede all other elements");
if (alias == "global") {
- Error_GlobalNamespaceRedefined (loc);
+ Error_GlobalNamespaceRedefined (loc, Report);
return;
}
} else {
foreach (UsingAliasEntry entry in using_aliases) {
if (uae.Alias == entry.Alias) {
- Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
- Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
+ Compiler.Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
+ Compiler.Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
entry.Alias);
return;
}
return result.Keys;
}
- static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
+ void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
{
- Report.SymbolRelatedToPreviousError (t1.Type);
- Report.SymbolRelatedToPreviousError (t2.Type);
- Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
+ Compiler.Report.SymbolRelatedToPreviousError (t1.Type);
+ Compiler.Report.SymbolRelatedToPreviousError (t2.Type);
+ Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
name, t1.GetSignatureForError (), t2.GetSignatureForError ());
}
//
// Check whether it's in the namespace.
//
- FullNamedExpression fne = ns.Lookup (name, loc);
+ FullNamedExpression fne = ns.Lookup (Compiler, name, loc);
//
// Check aliases.
if (Doppelganger != null) {
// TODO: Namespace has broken location
//Report.SymbolRelatedToPreviousError (fne.Location, null);
- Report.SymbolRelatedToPreviousError (ue.Location, null);
- Report.Error (576, loc,
+ Compiler.Report.SymbolRelatedToPreviousError (ue.Location, null);
+ Compiler.Report.Error (576, loc,
"Namespace `{0}' contains a definition with same name as alias `{1}'",
GetSignatureForError (), name);
} else {
//
FullNamedExpression match = null;
foreach (Namespace using_ns in GetUsingTable ()) {
- match = using_ns.Lookup (name, loc);
+ match = using_ns.Lookup (Compiler, name, loc);
if (match == null || !(match is TypeExpr))
continue;
if (fne != null) {
Console.WriteLine (" Try using -pkg:" + s);
}
- public static void Error_GlobalNamespaceRedefined (Location loc)
+ public static void Error_GlobalNamespaceRedefined (Location loc, Report Report)
{
Report.Error (1681, loc, "You cannot redefine the global extern alias");
}
- public static void Error_NamespaceNotFound (Location loc, string name)
+ public static void Error_NamespaceNotFound (Location loc, string name, Report Report)
{
Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
name);
#region IMemberContext Members
+ public CompilerContext Compiler {
+ get { return RootContext.ToplevelTypes.Compiler; }
+ }
+
public Type CurrentType {
get { return SlaveDeclSpace.CurrentType; }
}
protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
{
if (TypeManager.generic_nullable_type == null) {
- TypeManager.generic_nullable_type = TypeManager.CoreLookupType (
+ TypeManager.generic_nullable_type = TypeManager.CoreLookupType (ec.Compiler,
"System", "Nullable`1", Kind.Struct, true);
}
return new LiftedNull (nullable, loc);
}
- public static Expression CreateFromExpression (Expression e)
+ public static Expression CreateFromExpression (ResolveContext ec, Expression e)
{
- Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
+ ec.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
TypeManager.CSharpName (e.Type));
return ReducedExpression.Create (Create (e.Type, e.Location), e);
args.Add (new Argument (this));
args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
- return CreateExpressionFactoryCall ("Constant", args);
+ return CreateExpressionFactoryCall (ec, "Constant", args);
}
public override void Emit (EmitContext ec)
// with the null literal *outside* of a generics context and
// inlines that as true or false.
//
- Expression CreateNullConstant (Expression expr)
+ Expression CreateNullConstant (ResolveContext ec, Expression expr)
{
// FIXME: Handle side effect constants
Constant c = new BoolConstant (Oper == Operator.Inequality, loc);
if ((Oper & Operator.EqualityMask) != 0) {
- Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is `{1}'",
+ ec.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is `{1}'",
expr.GetSignatureForError (), c.AsString ());
} else {
- Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
+ ec.Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
expr.GetSignatureForError (), c.AsString ());
}
return this;
if ((Oper & Operator.LogicalMask) != 0) {
- Error_OperatorCannotBeApplied (left, right);
+ Error_OperatorCannotBeApplied (ec, left, right);
return null;
}
left = LiftedNull.Create (right.Type, left.Location);
if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask)) != 0)
- return LiftedNull.CreateFromExpression (res_expr);
+ return LiftedNull.CreateFromExpression (ec, res_expr);
//
// Value types and null comparison
//
if (right_unwrap == null || (Oper & Operator.RelationalMask) != 0)
- return CreateNullConstant (right_orig).Resolve (ec);
+ return CreateNullConstant (ec, right_orig).Resolve (ec);
}
if (right_null_lifted) {
right = LiftedNull.Create (left.Type, right.Location);
if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask)) != 0)
- return LiftedNull.CreateFromExpression (res_expr);
+ return LiftedNull.CreateFromExpression (ec, res_expr);
//
// Value types and null comparison
//
if (left_unwrap == null || (Oper & Operator.RelationalMask) != 0)
- return CreateNullConstant (left_orig).Resolve (ec);
+ return CreateNullConstant (ec, left_orig).Resolve (ec);
}
return res_expr;
public override Expression CreateExpressionTree (ResolveContext ec)
{
if (left.Type == TypeManager.null_type)
- Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
+ ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
UserCast uc = left as UserCast;
Expression conversion = null;
Arguments c_args = new Arguments (2);
c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
c_args.Add (new Argument (left.CreateExpressionTree (ec)));
- conversion = CreateExpressionFactoryCall ("Lambda", c_args);
+ conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
}
Arguments args = new Arguments (3);
if (conversion != null)
args.Add (new Argument (conversion));
- return CreateExpressionFactoryCall ("Coalesce", args);
+ return CreateExpressionFactoryCall (ec, "Coalesce", args);
}
Expression ConvertExpression (ResolveContext ec)
Expression e = ConvertExpression (ec);
if (e == null) {
- Binary.Error_OperatorCannotBeApplied (left, right, "??", loc);
+ Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
return null;
}
builder = mb.DefineParameter (0, ParameterAttributes.None, "");
}
catch (ArgumentOutOfRangeException) {
- Report.RuntimeMissingSupport (location, "custom attributes on the return type");
+ RootContext.ToplevelTypes.Compiler.Report.RuntimeMissingSupport (location, "custom attributes on the return type");
}
}
public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
{
if (a.Type == pa.CLSCompliant) {
- Report.Warning (3023, 1, a.Location, "CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead");
+ RootContext.ToplevelTypes.Compiler.Report.Warning (3023, 1, a.Location,
+ "CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead");
}
// This occurs after Warning -28
return null;
if (!parameter_type.IsArray || parameter_type.GetArrayRank () != 1) {
- Report.Error (225, Location, "The params parameter must be a single dimensional array");
+ ec.Compiler.Report.Error (225, Location, "The params parameter must be a single dimensional array");
return null;
}
public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
{
+ Report Report = RootContext.ToplevelTypes.Compiler.Report;
+
if (a.Type == pa.In && ModFlags == Modifier.OUT) {
Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
return;
(TypeManager.IsNullableType (parameter_type) &&
Convert.ImplicitNulableConversion (ec, default_expr, parameter_type) != EmptyExpression.Null);
} else {
- Report.Error (1736, default_expr.Location,
+ rc.Compiler.Report.Error (1736, default_expr.Location,
"The expression being assigned to optional parameter `{0}' must be a constant or default value",
Name);
is_valid = true;
if (!is_valid) {
default_expr = null;
- Report.Error (1763, Location,
+ ec.Compiler.Report.Error (1763, Location,
"Optional parameter `{0}' of type `{1}' can only be initialized with `null'",
Name, GetSignatureForError ());
}
Constant c = value.ConvertImplicitly (parameter_type);
if (c == null) {
if (parameter_type == TypeManager.object_type) {
- Report.Error (1763, Location,
+ rc.Compiler.Report.Error (1763, Location,
"Optional parameter `{0}' of type `{1}' can only be initialized with `null'",
Name, GetSignatureForError ());
} else {
- Report.Error (1750, Location,
+ rc.Compiler.Report.Error (1750, Location,
"Optional parameter value `{0}' cannot be converted to parameter type `{1}'",
value.GetValue (), GetSignatureForError ());
}
if ((modFlags & Parameter.Modifier.ISBYREF) != 0 &&
TypeManager.IsSpecialType (parameter_type)) {
- Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
+ rc.Compiler.Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
GetSignatureForError ());
return null;
}
return parameter_type;
if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
- Report.Error (721, Location, "`{0}': static types cannot be used as parameters",
+ rc.Compiler.Report.Error (721, Location, "`{0}': static types cannot be used as parameters",
texpr.GetSignatureForError ());
return parameter_type;
}
if ((modFlags & Modifier.This) != 0 && (parameter_type.IsPointer || TypeManager.IsDynamicType (parameter_type))) {
- Report.Error (1103, Location, "The extension method cannot be of type `{0}'",
+ rc.Compiler.Report.Error (1103, Location, "The extension method cannot be of type `{0}'",
TypeManager.CSharpName (parameter_type));
}
if (AttributeTester.IsClsCompliant (parameter_type))
return;
- Report.Warning (3001, 1, Location, "Argument type `{0}' is not CLS-compliant", GetSignatureForError ());
+ RootContext.ToplevelTypes.Compiler.Report.Warning (3001, 1, Location, "Argument type `{0}' is not CLS-compliant", GetSignatureForError ());
}
public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
HoistedVariableReference = null;
if ((modFlags & Modifier.ISBYREF) != 0)
- Report.Error (1951, Location, "An expression tree parameter cannot use `ref' or `out' modifier");
+ ec.Report.Error (1951, Location, "An expression tree parameter cannot use `ref' or `out' modifier");
LocalInfo variable = ec.CurrentBlock.AddTemporaryVariable (
ResolveParameterExpressionType (ec, Location), Location);
new TypeExpression (parameter_type, Location), Location)));
arguments.Add (new Argument (new StringConstant (Name, Location)));
return new SimpleAssign (ExpressionTreeVariableReference (),
- Expression.CreateExpressionFactoryCall ("Parameter", null, arguments, Location));
+ Expression.CreateExpressionFactoryCall (ec, "Parameter", null, arguments, Location));
}
public Expression DefaultValue {
Type p_type = TypeManager.parameter_expression_type;
if (p_type == null) {
- p_type = TypeManager.CoreLookupType ("System.Linq.Expressions", "ParameterExpression", Kind.Class, true);
+ p_type = TypeManager.CoreLookupType (ec.Compiler, "System.Linq.Expressions", "ParameterExpression", Kind.Class, true);
TypeManager.parameter_expression_type = p_type;
}
return parameter_expr_tree_type;
}
- public void Warning_UselessOptionalParameter ()
+ public void Warning_UselessOptionalParameter (Report Report)
{
Report.Warning (1066, 1, Location,
"The default value specified for optional parameter `{0}' will never be used",
if (base_name != parameters [j].Name)
continue;
- ErrorDuplicateName (parameters [i]);
+ ErrorDuplicateName (parameters[i], RootContext.ToplevelTypes.Compiler.Report);
i = j;
}
}
for (int i = 0; i < last_filled; ++i) {
while (p.Name == all_params [i].Name) {
if (checkConflicts && i < userParams.Count) {
- Report.Error (316, userParams [i].Location,
+ RootContext.ToplevelTypes.Compiler.Report.Error (316, userParams[i].Location,
"The parameter name `{0}' conflicts with a compiler generated name", p.Name);
}
p.Name = '_' + p.Name;
return parameters;
}
- protected virtual void ErrorDuplicateName (Parameter p)
+ protected virtual void ErrorDuplicateName (Parameter p, Report Report)
{
Report.Error (100, p.Location, "The parameter name `{0}' is a duplicate", p.Name);
}
/// Verifies that any pending abstract methods or interface methods
/// were implemented.
/// </summary>
- public bool VerifyPendingMethods ()
+ public bool VerifyPendingMethods (Report Report)
{
int top = pending_implementations.Length;
bool errors = false;
namespace Mono.CSharp {
- /// <summary>
- /// This class is used to report errors and warnings t te user.
- /// </summary>
+ //
+ // Errors and warnings manager
+ //
public class Report {
- /// <summary>
- /// Errors encountered so far
- /// </summary>
- static public int Errors;
-
- /// <summary>
- /// Warnings encountered so far
- /// </summary>
- static public int Warnings;
-
/// <summary>
/// Whether errors should be throw an exception
/// </summary>
- static public bool Fatal;
+ public bool Fatal;
/// <summary>
/// Whether warnings should be considered errors
/// </summary>
- static public bool WarningsAreErrors;
- static ArrayList warnings_as_error;
- static ArrayList warnings_only;
+ public bool WarningsAreErrors;
+ ArrayList warnings_as_error;
+ ArrayList warnings_only;
- /// <summary>
- /// Whether to dump a stack trace on errors.
- /// </summary>
- static public bool Stacktrace;
-
- static public TextWriter Stderr = Console.Error;
-
- //
- // If the 'expected' error code is reported then the
- // compilation succeeds.
- //
- // Used for the test suite to excercise the error codes
- //
- static int expected_error = 0;
+ public static int DebugFlags = 0;
//
// Keeps track of the warnings that we are ignoring
//
- public static Hashtable warning_ignore_table;
+ public Hashtable warning_ignore_table;
- static Hashtable warning_regions_table;
+ Hashtable warning_regions_table;
- //
- // This is used to save/restore the error state. When the
- // error stack contains elements, warnings and errors are not
- // reported to the user. This is used by the Lambda expression
- // support to compile the code with various parameter values.
- // A stack because of `Report.Errors == errors;'
- //
- static Stack error_stack;
- static Stack warning_stack;
- static bool reporting_disabled;
-
- static int warning_level;
+ int warning_level;
+
+ ReportPrinter printer;
+
+ int reporting_disabled;
/// <summary>
/// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
/// </summary>
- static ArrayList extra_information = new ArrayList ();
+ ArrayList extra_information = new ArrayList ();
//
// IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
Array.Sort (AllWarnings);
}
- public static void Reset ()
+ public Report (ReportPrinter printer)
{
- Errors = Warnings = 0;
- WarningsAreErrors = false;
- warning_ignore_table = null;
- warning_regions_table = null;
- reporting_disabled = false;
- error_stack = warning_stack = null;
- warnings_as_error = null;
- warnings_only = null;
+ if (printer == null)
+ throw new ArgumentNullException ("printer");
+
+ this.printer = printer;
+ warning_level = 4;
}
- public static void DisableReporting ()
+ public void DisableReporting ()
{
- if (error_stack == null)
- error_stack = new Stack ();
- error_stack.Push (Errors);
-
- if (Warnings > 0) {
- if (warning_stack == null)
- warning_stack = new Stack ();
- warning_stack.Push (Warnings);
- }
-
- reporting_disabled = true;
+ ++reporting_disabled;
}
- public static void EnableReporting ()
+ public void EnableReporting ()
{
- if (warning_stack != null && warning_stack.Count > 0)
- Warnings = (int) warning_stack.Pop ();
- else
- Warnings = 0;
-
- Errors = (int) error_stack.Pop ();
- if (error_stack.Count == 0) {
- reporting_disabled = false;
- }
+ --reporting_disabled;
}
- public static IMessageRecorder msg_recorder;
-
- public static IMessageRecorder SetMessageRecorder (IMessageRecorder recorder)
+ public void FeatureIsNotAvailable (Location loc, string feature)
{
- IMessageRecorder previous = msg_recorder;
- msg_recorder = recorder;
- return previous;
+ string version;
+ switch (RootContext.Version) {
+ case LanguageVersion.ISO_1:
+ version = "1.0";
+ break;
+ case LanguageVersion.ISO_2:
+ version = "2.0";
+ break;
+ case LanguageVersion.V_3:
+ version = "3.0";
+ break;
+ default:
+ throw new InternalErrorException ("Invalid feature version", RootContext.Version);
+ }
+
+ Error (1644, loc,
+ "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
+ feature, version);
}
- public interface IMessageRecorder
+ public void FeatureIsNotSupported (Location loc, string feature)
{
- bool IsEmpty { get; }
- void EndSession ();
- void AddMessage (AbstractMessage msg);
- bool PrintMessages ();
+ Error (1644, loc,
+ "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
+ feature);
+ }
+
+ static bool IsValidWarning (int code)
+ {
+ return Array.BinarySearch (AllWarnings, code) >= 0;
}
- //
- // Default message recorder, it uses two types of message groups.
- // Common messages: messages reported in all sessions.
- // Merged messages: union of all messages in all sessions.
- //
- public struct MessageRecorder : IMessageRecorder
+ bool IsWarningEnabled (int code, int level, Location loc)
{
- ArrayList session_messages;
- //
- // A collection of exactly same messages reported in all sessions
- //
- ArrayList common_messages;
-
- //
- // A collection of unique messages reported in all sessions
- //
- ArrayList merged_messages;
-
- public void EndSession ()
- {
- if (session_messages == null)
- return;
+ if (WarningLevel < level)
+ return false;
- //
- // Handles the first session
- //
- if (common_messages == null) {
- common_messages = new ArrayList (session_messages);
- merged_messages = session_messages;
- session_messages = null;
- return;
+ if (warning_ignore_table != null) {
+ if (warning_ignore_table.Contains (code)) {
+ return false;
}
+ }
- //
- // Store common messages if any
- //
- for (int i = 0; i < common_messages.Count; ++i) {
- AbstractMessage cmsg = (AbstractMessage) common_messages [i];
- bool common_msg_found = false;
- foreach (AbstractMessage msg in session_messages) {
- if (cmsg.Equals (msg)) {
- common_msg_found = true;
- break;
- }
- }
+ if (warning_regions_table == null || loc.IsNull)
+ return true;
- if (!common_msg_found)
- common_messages.RemoveAt (i);
- }
+ WarningRegions regions = (WarningRegions) warning_regions_table [loc.Name];
+ if (regions == null)
+ return true;
- //
- // Merge session and previous messages
- //
- for (int i = 0; i < session_messages.Count; ++i) {
- AbstractMessage msg = (AbstractMessage) session_messages [i];
- bool msg_found = false;
- for (int ii = 0; ii < merged_messages.Count; ++ii) {
- if (msg.Equals (merged_messages [ii])) {
- msg_found = true;
- break;
- }
- }
+ return regions.IsWarningEnabled (code, loc.Row);
+ }
- if (!msg_found)
- merged_messages.Add (msg);
- }
- }
+ bool IsWarningAsError (int code)
+ {
+ bool is_error = WarningsAreErrors;
- public void AddMessage (AbstractMessage msg)
- {
- if (session_messages == null)
- session_messages = new ArrayList ();
+ // Check specific list
+ if (warnings_as_error != null)
+ is_error |= warnings_as_error.Contains (code);
- session_messages.Add (msg);
- }
+ // Ignore excluded warnings
+ if (warnings_only != null && warnings_only.Contains (code))
+ is_error = false;
- public bool IsEmpty {
- get {
- return merged_messages == null && common_messages == null;
- }
- }
+ return is_error;
+ }
+
+ public void RuntimeMissingSupport (Location loc, string feature)
+ {
+ Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
+ }
- //
- // Prints collected messages, common messages have a priority
- //
- public bool PrintMessages ()
- {
- ArrayList messages_to_print = merged_messages;
- if (common_messages != null && common_messages.Count > 0) {
- messages_to_print = common_messages;
- }
+ /// <summary>
+ /// In most error cases is very useful to have information about symbol that caused the error.
+ /// Call this method before you call Report.Error when it makes sense.
+ /// </summary>
+ public void SymbolRelatedToPreviousError (Location loc, string symbol)
+ {
+ SymbolRelatedToPreviousError (loc.ToString (), symbol);
+ }
- if (messages_to_print == null)
- return false;
+ public void SymbolRelatedToPreviousError (MemberInfo mi)
+ {
+ if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
+ return;
+
+ Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
+ if (TypeManager.IsDelegateType (dt)) {
+ SymbolRelatedToPreviousError (dt);
+ return;
+ }
+
+ DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
+ if (temp_ds == null) {
+ SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
+ } else {
+ MethodBase mb = mi as MethodBase;
+ if (mb != null) {
+ mb = TypeManager.DropGenericMethodArguments (mb);
+ IMethodData md = TypeManager.GetMethod (mb);
+ if (md != null)
+ SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
- foreach (AbstractMessage msg in messages_to_print)
- msg.Print ();
+ return;
+ }
- return true;
+ // FIXME: Completely wrong, it has to use FindMembers
+ MemberCore mc = temp_ds.GetDefinition (mi.Name);
+ if (mc != null)
+ SymbolRelatedToPreviousError (mc);
}
}
-
- public abstract class AbstractMessage
+
+ public void SymbolRelatedToPreviousError (MemberCore mc)
{
- readonly string[] extra_info;
- protected readonly int code;
- protected readonly Location location;
- readonly string message;
+ SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
+ }
- protected AbstractMessage (int code, Location loc, string msg, ArrayList extraInfo)
- {
- this.code = code;
- if (code < 0)
- this.code = 8000 - code;
+ public void SymbolRelatedToPreviousError (Type type)
+ {
+ if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
+ return;
+
+ type = TypeManager.DropGenericTypeArguments (type);
- this.location = loc;
- this.message = msg;
- if (extraInfo.Count != 0) {
- this.extra_info = (string[])extraInfo.ToArray (typeof (string));
+ if (TypeManager.IsGenericParameter (type)) {
+ TypeParameter tp = TypeManager.LookupTypeParameter (type);
+ if (tp != null) {
+ SymbolRelatedToPreviousError (tp.Location, "");
+ return;
}
}
- protected AbstractMessage (AbstractMessage aMsg)
- {
- this.code = aMsg.code;
- this.location = aMsg.location;
- this.message = aMsg.message;
- this.extra_info = aMsg.extra_info;
+ if (type is TypeBuilder) {
+ DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
+ SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
+ } else if (TypeManager.HasElementType (type)) {
+ SymbolRelatedToPreviousError (TypeManager.GetElementType (type));
+ } else {
+ SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
}
+ }
- static void Check (int code)
- {
- if (code == expected_error) {
- Environment.Exit (0);
- }
- }
+ void SymbolRelatedToPreviousError (string loc, string symbol)
+ {
+ string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
+ if (extra_information.Contains (msg))
+ return;
- public override bool Equals (object obj)
- {
- AbstractMessage msg = obj as AbstractMessage;
- if (msg == null)
- return false;
+ extra_information.Add (msg);
+ }
- return code == msg.code && location.Equals (msg.location) && message == msg.message;
+ public void AddWarningAsError (string warningId)
+ {
+ int id;
+ try {
+ id = int.Parse (warningId);
+ } catch {
+ id = -1;
}
- public override int GetHashCode ()
- {
- return code.GetHashCode ();
- }
+ if (!CheckWarningCode (id, warningId, Location.Null))
+ return;
- public abstract bool IsWarning { get; }
+ if (warnings_as_error == null)
+ warnings_as_error = new ArrayList ();
+
+ warnings_as_error.Add (id);
+ }
- public abstract string MessageType { get; }
+ public void RemoveWarningAsError (string warningId)
+ {
+ int id;
+ try {
+ id = int.Parse (warningId);
+ } catch {
+ id = -1;
+ }
- public virtual void Print ()
- {
- if (msg_recorder != null) {
- //
- // This line is useful when debugging messages recorder
- //
- // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
- msg_recorder.AddMessage (this);
- return;
- }
+ if (!CheckWarningCode (id, warningId, Location.Null))
+ return;
- if (reporting_disabled)
- return;
+ if (warnings_only == null)
+ warnings_only = new ArrayList ();
- StringBuilder msg = new StringBuilder ();
- if (!location.IsNull) {
- msg.Append (location.ToString ());
- msg.Append (" ");
- }
- msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, message);
+ warnings_only.Add (id);
+ }
- //
- //
- if (Stderr == Console.Error)
- Stderr.WriteLine (ColorFormat (msg.ToString ()));
- else
- Stderr.WriteLine (msg.ToString ());
+ public bool CheckWarningCode (int code, Location loc)
+ {
+ return CheckWarningCode (code, code.ToString (), loc);
+ }
- if (extra_info != null) {
- foreach (string s in extra_info)
- Stderr.WriteLine (s + MessageType + ")");
- }
+ public bool CheckWarningCode (int code, string scode, Location loc)
+ {
+ if (IsValidWarning (code))
+ return true;
- if (Stacktrace)
- Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
+ Warning (1691, 1, loc, "`{0}' is not a valid warning number", scode);
+ return false;
+ }
- if (Fatal && !IsWarning)
- throw new Exception (message);
+ public void ExtraInformation (Location loc, string msg)
+ {
+ extra_information.Add (String.Format ("{0} {1}", loc, msg));
+ }
- Check (code);
- }
+ public WarningRegions RegisterWarningRegion (Location location)
+ {
+ if (warning_regions_table == null)
+ warning_regions_table = new Hashtable ();
- protected virtual string ColorFormat (string s)
- {
- return s;
+ WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
+ if (regions == null) {
+ regions = new WarningRegions ();
+ warning_regions_table.Add (location.Name, regions);
}
+ return regions;
}
- sealed class WarningMessage : AbstractMessage
+ public void Warning (int code, int level, Location loc, string message)
{
- readonly int Level;
+ if (reporting_disabled > 0)
+ return;
- public WarningMessage (int code, int level, Location loc, string message, ArrayList extra_info)
- : base (code, loc, message, extra_info)
- {
- Level = level;
- }
+ if (!IsWarningEnabled (code, level, loc))
+ return;
- public override bool IsWarning {
- get { return true; }
- }
+ AbstractMessage msg;
+ if (IsWarningAsError (code))
+ msg = new ErrorMessage (code, loc, message, extra_information);
+ else
+ msg = new WarningMessage (code, loc, message, extra_information);
- bool IsEnabled ()
- {
- if (WarningLevel < Level)
- return false;
+ extra_information.Clear ();
+ printer.Print (msg);
+ }
- if (warning_ignore_table != null) {
- if (warning_ignore_table.Contains (code)) {
- return false;
- }
- }
+ public void Warning (int code, int level, Location loc, string format, string arg)
+ {
+ Warning (code, level, loc, String.Format (format, arg));
+ }
- if (warning_regions_table == null || location.IsNull)
- return true;
+ public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
+ {
+ Warning (code, level, loc, String.Format (format, arg1, arg2));
+ }
- WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
- if (regions == null)
- return true;
+ public void Warning (int code, int level, Location loc, string format, params object[] args)
+ {
+ Warning (code, level, loc, String.Format (format, args));
+ }
- return regions.IsWarningEnabled (code, location.Row);
- }
+ public void Warning (int code, int level, string message)
+ {
+ Warning (code, level, Location.Null, message);
+ }
- bool IsErrorWarning {
- get {
- bool is_error = WarningsAreErrors;
+ public void Warning (int code, int level, string format, string arg)
+ {
+ Warning (code, level, Location.Null, format, arg);
+ }
- // Check specific list
- if (warnings_as_error != null)
- is_error |= warnings_as_error.Contains (code);
+ public void Warning (int code, int level, string format, string arg1, string arg2)
+ {
+ Warning (code, level, Location.Null, format, arg1, arg2);
+ }
- // Ignore excluded warnings
- if (warnings_only != null && warnings_only.Contains (code))
- is_error = false;
+ public void Warning (int code, int level, string format, params string[] args)
+ {
+ Warning (code, level, Location.Null, String.Format (format, args));
+ }
- return is_error;
- }
- }
+ //
+ // Warnings encountered so far
+ //
+ public int Warnings {
+ get { return printer.WarningsCount; }
+ }
- public override void Print ()
- {
- if (!IsEnabled ())
- return;
+ public void Error (int code, Location loc, string error)
+ {
+ if (reporting_disabled > 0)
+ return;
- if (IsErrorWarning) {
- new ErrorMessage (this).Print ();
- return;
- }
+ ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
+ extra_information.Clear ();
- Warnings++;
- base.Print ();
- }
+ printer.Print (msg);
- public override string MessageType {
- get {
- return "warning";
- }
- }
+ if (Fatal)
+ throw new Exception (msg.Text);
}
- static int NameToCode (string s)
+ public void Error (int code, Location loc, string format, string arg)
{
- switch (s){
- case "black":
- return 0;
- case "red":
- return 1;
- case "green":
- return 2;
- case "yellow":
- return 3;
- case "blue":
- return 4;
- case "magenta":
- return 5;
- case "cyan":
- return 6;
- case "grey":
- case "white":
- return 7;
- }
- return 7;
+ Error (code, loc, String.Format (format, arg));
}
-
- //
- // maps a color name to its xterm color code
- //
- static string GetForeground (string s)
- {
- string highcode;
- if (s.StartsWith ("bright")){
- highcode = "1;";
- s = s.Substring (6);
- } else
- highcode = "";
-
- return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
+ public void Error (int code, Location loc, string format, string arg1, string arg2)
+ {
+ Error (code, loc, String.Format (format, arg1, arg2));
}
- static string GetBackground (string s)
+ public void Error (int code, Location loc, string format, params object[] args)
{
- return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
+ Error (code, loc, String.Format (format, args));
}
-
- sealed class ErrorMessage : AbstractMessage
- {
- static string prefix, postfix;
-
- static ErrorMessage ()
- {
- string term = Environment.GetEnvironmentVariable ("TERM");
- bool xterm_colors = false;
-
- switch (term){
- case "xterm":
- case "rxvt":
- case "rxvt-unicode":
- if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
- xterm_colors = true;
- }
- break;
-
- case "xterm-color":
- xterm_colors = true;
- break;
- }
- if (!xterm_colors)
- return;
-
- if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
- return;
-
- string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
- if (config == null){
- config = "errors=red";
- //config = "brightwhite,red";
- }
-
- if (config == "disable")
- return;
-
- if (!config.StartsWith ("errors="))
- return;
-
- config = config.Substring (7);
-
- int p = config.IndexOf (",");
- if (p == -1)
- prefix = GetForeground (config);
- else
- prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
- postfix = "\x001b[0m";
- }
- public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
- : base (code, loc, message, extraInfo)
- {
- }
-
- public ErrorMessage (AbstractMessage aMsg)
- : base (aMsg)
- {
- }
-
- protected override string ColorFormat (string s)
- {
- if (prefix != null)
- return prefix + s + postfix;
- return s;
- }
-
- public override void Print()
- {
- Errors++;
- base.Print ();
- }
-
- public override bool IsWarning {
- get { return false; }
- }
-
- public override string MessageType {
- get {
- return "error";
- }
- }
+ public void Error (int code, string error)
+ {
+ Error (code, Location.Null, error);
}
- public static void FeatureIsNotAvailable (Location loc, string feature)
+ public void Error (int code, string format, string arg)
{
- string version;
- switch (RootContext.Version) {
- case LanguageVersion.ISO_1:
- version = "1.0";
- break;
- case LanguageVersion.ISO_2:
- version = "2.0";
- break;
- case LanguageVersion.V_3:
- version = "3.0";
- break;
- default:
- throw new InternalErrorException ("Invalid feature version", RootContext.Version);
- }
-
- Report.Error (1644, loc,
- "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
- feature, version);
+ Error (code, Location.Null, format, arg);
}
- public static void FeatureIsNotSupported (Location loc, string feature)
+ public void Error (int code, string format, string arg1, string arg2)
{
- Report.Error (1644, loc,
- "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
- feature);
+ Error (code, Location.Null, format, arg1, arg2);
}
-
- public static string FriendlyStackTrace (Exception e)
+
+ public void Error (int code, string format, params string[] args)
{
- return FriendlyStackTrace (new StackTrace (e, true));
- }
-
- static string FriendlyStackTrace (StackTrace t)
- {
- StringBuilder sb = new StringBuilder ();
-
- bool foundUserCode = false;
-
- for (int i = 0; i < t.FrameCount; i++) {
- StackFrame f = t.GetFrame (i);
- MethodBase mb = f.GetMethod ();
-
- if (!foundUserCode && mb.ReflectedType == typeof (Report))
- continue;
-
- foundUserCode = true;
-
- sb.Append ("\tin ");
-
- if (f.GetFileLineNumber () > 0)
- sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
-
- sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
-
- bool first = true;
- foreach (ParameterInfo pi in mb.GetParameters ()) {
- if (!first)
- sb.Append (", ");
- first = false;
-
- sb.Append (TypeManager.CSharpName (pi.ParameterType));
- }
- sb.Append (")\n");
- }
-
- return sb.ToString ();
+ Error (code, Location.Null, String.Format (format, args));
}
- public static void StackTrace ()
- {
- Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
+ //
+ // Errors encountered so far
+ //
+ public int Errors {
+ get { return printer.ErrorsCount; }
}
- static bool IsValidWarning (int code)
- {
- return Array.BinarySearch (AllWarnings, code) >= 0;
+ public ReportPrinter Printer {
+ get { return printer; }
}
-
- static public void RuntimeMissingSupport (Location loc, string feature)
+
+ public void SetIgnoreWarning (int code)
{
- Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
+ if (warning_ignore_table == null)
+ warning_ignore_table = new Hashtable ();
+
+ warning_ignore_table [code] = true;
}
- /// <summary>
- /// In most error cases is very useful to have information about symbol that caused the error.
- /// Call this method before you call Report.Error when it makes sense.
- /// </summary>
- static public void SymbolRelatedToPreviousError (Location loc, string symbol)
+ public ReportPrinter SetPrinter (ReportPrinter printer)
{
- SymbolRelatedToPreviousError (loc.ToString (), symbol);
+ ReportPrinter old = this.printer;
+ this.printer = printer;
+ return old;
+ }
+
+ public int WarningLevel {
+ get {
+ return warning_level;
+ }
+ set {
+ warning_level = value;
+ }
}
- static public void SymbolRelatedToPreviousError (MemberInfo mi)
+ [Conditional ("MCS_DEBUG")]
+ static public void Debug (string message, params object[] args)
{
- if (reporting_disabled)
+ Debug (4, message, args);
+ }
+
+ [Conditional ("MCS_DEBUG")]
+ static public void Debug (int category, string message, params object[] args)
+ {
+ if ((category & DebugFlags) == 0)
return;
- Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
- if (TypeManager.IsDelegateType (dt)) {
- SymbolRelatedToPreviousError (dt);
- return;
- }
-
- DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
- if (temp_ds == null) {
- SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
- } else {
- MethodBase mb = mi as MethodBase;
- if (mb != null) {
- mb = TypeManager.DropGenericMethodArguments (mb);
- IMethodData md = TypeManager.GetMethod (mb);
- if (md != null)
- SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
+ StringBuilder sb = new StringBuilder (message);
- return;
- }
+ if ((args != null) && (args.Length > 0)) {
+ sb.Append (": ");
- // FIXME: Completely wrong, it has to use FindMembers
- MemberCore mc = temp_ds.GetDefinition (mi.Name);
- if (mc != null)
- SymbolRelatedToPreviousError (mc);
+ bool first = true;
+ foreach (object arg in args) {
+ if (first)
+ first = false;
+ else
+ sb.Append (", ");
+ if (arg == null)
+ sb.Append ("null");
+ else if (arg is ICollection)
+ sb.Append (PrintCollection ((ICollection) arg));
+ else
+ sb.Append (arg);
+ }
}
- }
- static public void SymbolRelatedToPreviousError (MemberCore mc)
- {
- SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
+ Console.WriteLine (sb.ToString ());
}
- static public void SymbolRelatedToPreviousError (Type type)
+ static public string PrintCollection (ICollection collection)
{
- if (reporting_disabled)
- return;
+ StringBuilder sb = new StringBuilder ();
- type = TypeManager.DropGenericTypeArguments (type);
+ sb.Append (collection.GetType ());
+ sb.Append ("(");
- if (TypeManager.IsGenericParameter (type)) {
- TypeParameter tp = TypeManager.LookupTypeParameter (type);
- if (tp != null) {
- SymbolRelatedToPreviousError (tp.Location, "");
- return;
- }
+ bool first = true;
+ foreach (object o in collection) {
+ if (first)
+ first = false;
+ else
+ sb.Append (", ");
+ sb.Append (o);
}
- if (type is TypeBuilder) {
- DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
- SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
- } else if (TypeManager.HasElementType (type)) {
- SymbolRelatedToPreviousError (TypeManager.GetElementType (type));
- } else {
- SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
- }
+ sb.Append (")");
+ return sb.ToString ();
}
+ }
+
+ public abstract class AbstractMessage
+ {
+ readonly string[] extra_info;
+ protected readonly int code;
+ protected readonly Location location;
+ readonly string message;
- static void SymbolRelatedToPreviousError (string loc, string symbol)
+ protected AbstractMessage (int code, Location loc, string msg, ArrayList extraInfo)
{
- string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
- if (extra_information.Contains (msg))
- return;
+ this.code = code;
+ if (code < 0)
+ this.code = 8000 - code;
- extra_information.Add (msg);
+ this.location = loc;
+ this.message = msg;
+ if (extraInfo.Count != 0) {
+ this.extra_info = (string[])extraInfo.ToArray (typeof (string));
+ }
}
- public static void AddWarningAsError (string warningId)
+ protected AbstractMessage (AbstractMessage aMsg)
{
- int id;
- try {
- id = int.Parse (warningId);
- } catch {
- id = -1;
- }
-
- if (!CheckWarningCode (id, warningId, Location.Null))
- return;
+ this.code = aMsg.code;
+ this.location = aMsg.location;
+ this.message = aMsg.message;
+ this.extra_info = aMsg.extra_info;
+ }
- if (warnings_as_error == null)
- warnings_as_error = new ArrayList ();
-
- warnings_as_error.Add (id);
+ public int Code {
+ get { return code; }
}
- public static void RemoveWarningAsError (string warningId)
+ public override bool Equals (object obj)
{
- int id;
- try {
- id = int.Parse (warningId);
- } catch {
- id = -1;
- }
-
- if (!CheckWarningCode (id, warningId, Location.Null))
- return;
+ AbstractMessage msg = obj as AbstractMessage;
+ if (msg == null)
+ return false;
- if (warnings_only == null)
- warnings_only = new ArrayList ();
+ return code == msg.code && location.Equals (msg.location) && message == msg.message;
+ }
- warnings_only.Add (id);
+ public override int GetHashCode ()
+ {
+ return code.GetHashCode ();
}
- public static bool CheckWarningCode (int code, Location loc)
- {
- return CheckWarningCode (code, code.ToString (), loc);
+ public abstract bool IsWarning { get; }
+
+ public Location Location {
+ get { return location; }
}
- public static bool CheckWarningCode (int code, string scode, Location loc)
- {
- if (IsValidWarning (code))
- return true;
+ public abstract string MessageType { get; }
- Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", scode);
- return false;
+ public string[] RelatedSymbols {
+ get { return extra_info; }
}
- public static void ExtraInformation (Location loc, string msg)
- {
- extra_information.Add (String.Format ("{0} {1}", loc, msg));
+ public string Text {
+ get { return message; }
}
+ }
- public static WarningRegions RegisterWarningRegion (Location location)
+ sealed class WarningMessage : AbstractMessage
+ {
+ public WarningMessage (int code, Location loc, string message, ArrayList extra_info)
+ : base (code, loc, message, extra_info)
{
- if (warning_regions_table == null)
- warning_regions_table = new Hashtable ();
-
- WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
- if (regions == null) {
- regions = new WarningRegions ();
- warning_regions_table.Add (location.Name, regions);
- }
- return regions;
}
- static public void Warning (int code, int level, Location loc, string message)
- {
- WarningMessage w = new WarningMessage (code, level, loc, message, extra_information);
- extra_information.Clear ();
- w.Print ();
+ public override bool IsWarning {
+ get { return true; }
}
- static public void Warning (int code, int level, Location loc, string format, string arg)
- {
- WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg), extra_information);
- extra_information.Clear ();
- w.Print ();
+ public override string MessageType {
+ get {
+ return "warning";
+ }
}
+ }
- static public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
+ sealed class ErrorMessage : AbstractMessage
+ {
+ public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
+ : base (code, loc, message, extraInfo)
{
- WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg1, arg2), extra_information);
- extra_information.Clear ();
- w.Print ();
}
- static public void Warning (int code, int level, Location loc, string format, params object[] args)
+ public ErrorMessage (AbstractMessage aMsg)
+ : base (aMsg)
{
- WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, args), extra_information);
- extra_information.Clear ();
- w.Print ();
}
- static public void Warning (int code, int level, string message)
- {
- Warning (code, level, Location.Null, message);
+ public override bool IsWarning {
+ get { return false; }
}
- static public void Warning (int code, int level, string format, string arg)
- {
- Warning (code, level, Location.Null, format, arg);
+ public override string MessageType {
+ get {
+ return "error";
+ }
}
+ }
+
+ //
+ // Generic base for any message writer
+ //
+ public abstract class ReportPrinter
+ {
+ /// <summary>
+ /// Whether to dump a stack trace on errors.
+ /// </summary>
+ public bool Stacktrace;
+
+ public int WarningsCount { get; private set; }
+ public int ErrorsCount { get; private set; }
- static public void Warning (int code, int level, string format, string arg1, string arg2)
+ protected virtual string FormatText (string txt)
{
- Warning (code, level, Location.Null, format, arg1, arg2);
+ return txt;
}
- static public void Warning (int code, int level, string format, params string[] args)
- {
- Warning (code, level, Location.Null, String.Format (format, args));
+ //
+ // When (symbols related to previous ...) can be used
+ //
+ public virtual bool HasRelatedSymbolSupport {
+ get { return true; }
}
- static public void Error (int code, Location loc, string error)
+ public virtual void Print (AbstractMessage msg)
{
- new ErrorMessage (code, loc, error, extra_information).Print ();
- extra_information.Clear ();
+ if (msg.IsWarning)
+ ++WarningsCount;
+ else
+ ++ErrorsCount;
}
- static public void Error (int code, Location loc, string format, string arg)
+ protected void Print (AbstractMessage msg, TextWriter output)
{
- new ErrorMessage (code, loc, String.Format (format, arg), extra_information).Print ();
- extra_information.Clear ();
+ StringBuilder txt = new StringBuilder ();
+ if (!msg.Location.IsNull) {
+ txt.Append (msg.Location.ToString ());
+ txt.Append (" ");
+ }
+
+ txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
+
+ if (!msg.IsWarning)
+ output.WriteLine (FormatText (txt.ToString ()));
+ else
+ output.WriteLine (txt.ToString ());
+
+ if (msg.RelatedSymbols != null) {
+ foreach (string s in msg.RelatedSymbols)
+ output.WriteLine (s + msg.MessageType + ")");
+ }
}
+ }
+
+ //
+ // Default message recorder, it uses two types of message groups.
+ // Common messages: messages reported in all sessions.
+ // Merged messages: union of all messages in all sessions.
+ //
+ // Used by the Lambda expressions to compile the code with various
+ // parameter values, or by attribute resolver
+ //
+ class SessionReportPrinter : ReportPrinter
+ {
+ ArrayList session_messages;
+ //
+ // A collection of exactly same messages reported in all sessions
+ //
+ ArrayList common_messages;
+
+ //
+ // A collection of unique messages reported in all sessions
+ //
+ ArrayList merged_messages;
- static public void Error (int code, Location loc, string format, string arg1, string arg2)
+ public override void Print (AbstractMessage msg)
{
- new ErrorMessage (code, loc, String.Format (format, arg1, arg2), extra_information).Print ();
- extra_information.Clear ();
+ //
+ // This line is useful when debugging recorded messages
+ //
+ // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
+
+ if (session_messages == null)
+ session_messages = new ArrayList ();
+
+ session_messages.Add (msg);
+
+ base.Print (msg);
}
- static public void Error (int code, Location loc, string format, params object[] args)
+ public void EndSession ()
{
- Error (code, loc, String.Format (format, args));
+ if (session_messages == null)
+ return;
+
+ //
+ // Handles the first session
+ //
+ if (common_messages == null) {
+ common_messages = new ArrayList (session_messages);
+ merged_messages = session_messages;
+ session_messages = null;
+ return;
+ }
+
+ //
+ // Store common messages if any
+ //
+ for (int i = 0; i < common_messages.Count; ++i) {
+ AbstractMessage cmsg = (AbstractMessage) common_messages[i];
+ bool common_msg_found = false;
+ foreach (AbstractMessage msg in session_messages) {
+ if (cmsg.Equals (msg)) {
+ common_msg_found = true;
+ break;
+ }
+ }
+
+ if (!common_msg_found)
+ common_messages.RemoveAt (i);
+ }
+
+ //
+ // Merge session and previous messages
+ //
+ for (int i = 0; i < session_messages.Count; ++i) {
+ AbstractMessage msg = (AbstractMessage) session_messages[i];
+ bool msg_found = false;
+ for (int ii = 0; ii < merged_messages.Count; ++ii) {
+ if (msg.Equals (merged_messages[ii])) {
+ msg_found = true;
+ break;
+ }
+ }
+
+ if (!msg_found)
+ merged_messages.Add (msg);
+ }
}
- static public void Error (int code, string error)
- {
- Error (code, Location.Null, error);
+ public bool IsEmpty {
+ get {
+ return merged_messages == null && common_messages == null;
+ }
}
- static public void Error (int code, string format, string arg)
+ //
+ // Prints collected messages, common messages have a priority
+ //
+ public bool Merge (ReportPrinter dest)
{
- Error (code, Location.Null, format, arg);
+ ArrayList messages_to_print = merged_messages;
+ if (common_messages != null && common_messages.Count > 0) {
+ messages_to_print = common_messages;
+ }
+
+ if (messages_to_print == null)
+ return false;
+
+ foreach (AbstractMessage msg in messages_to_print)
+ dest.Print (msg);
+
+ return true;
}
+ }
- static public void Error (int code, string format, string arg1, string arg2)
+ class StreamReportPrinter : ReportPrinter
+ {
+ TextWriter writer;
+
+ public StreamReportPrinter (TextWriter writer)
{
- Error (code, Location.Null, format, arg1, arg2);
+ this.writer = writer;
}
- static public void Error (int code, string format, params string[] args)
+ public override void Print (AbstractMessage msg)
{
- Error (code, Location.Null, String.Format (format, args));
+ Print (msg, writer);
+ base.Print (msg);
}
+ }
+
+ class ConsoleReportPrinter : ReportPrinter
+ {
+ static readonly string prefix, postfix;
- static public void SetIgnoreWarning (int code)
+ static ConsoleReportPrinter ()
{
- if (warning_ignore_table == null)
- warning_ignore_table = new Hashtable ();
+ string term = Environment.GetEnvironmentVariable ("TERM");
+ bool xterm_colors = false;
+
+ switch (term){
+ case "xterm":
+ case "rxvt":
+ case "rxvt-unicode":
+ if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
+ xterm_colors = true;
+ }
+ break;
- warning_ignore_table [code] = true;
- }
-
- static public int ExpectedError {
- set {
- expected_error = value;
+ case "xterm-color":
+ xterm_colors = true;
+ break;
}
- get {
- return expected_error;
+ if (!xterm_colors)
+ return;
+
+ if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
+ return;
+
+ string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
+ if (config == null){
+ config = "errors=red";
+ //config = "brightwhite,red";
}
+
+ if (config == "disable")
+ return;
+
+ if (!config.StartsWith ("errors="))
+ return;
+
+ config = config.Substring (7);
+
+ int p = config.IndexOf (",");
+ if (p == -1)
+ prefix = GetForeground (config);
+ else
+ prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
+ postfix = "\x001b[0m";
}
-
- public static int WarningLevel {
- get {
- return warning_level;
- }
- set {
- warning_level = value;
+
+ static int NameToCode (string s)
+ {
+ switch (s) {
+ case "black":
+ return 0;
+ case "red":
+ return 1;
+ case "green":
+ return 2;
+ case "yellow":
+ return 3;
+ case "blue":
+ return 4;
+ case "magenta":
+ return 5;
+ case "cyan":
+ return 6;
+ case "grey":
+ case "white":
+ return 7;
}
+ return 7;
}
- public static int DebugFlags = 0;
-
- [Conditional ("MCS_DEBUG")]
- static public void Debug (string message, params object[] args)
+ //
+ // maps a color name to its xterm color code
+ //
+ static string GetForeground (string s)
{
- Debug (4, message, args);
+ string highcode;
+
+ if (s.StartsWith ("bright")) {
+ highcode = "1;";
+ s = s.Substring (6);
+ } else
+ highcode = "";
+
+ return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
}
-
- [Conditional ("MCS_DEBUG")]
- static public void Debug (int category, string message, params object[] args)
+
+ static string GetBackground (string s)
{
- if ((category & DebugFlags) == 0)
- return;
+ return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
+ }
- StringBuilder sb = new StringBuilder (message);
+ protected override string FormatText (string txt)
+ {
+ if (prefix != null)
+ return prefix + txt + postfix;
- if ((args != null) && (args.Length > 0)) {
- sb.Append (": ");
+ return txt;
+ }
+ static string FriendlyStackTrace (StackTrace t)
+ {
+ StringBuilder sb = new StringBuilder ();
+
+ bool foundUserCode = false;
+
+ for (int i = 0; i < t.FrameCount; i++) {
+ StackFrame f = t.GetFrame (i);
+ MethodBase mb = f.GetMethod ();
+
+ if (!foundUserCode && mb.ReflectedType == typeof (Report))
+ continue;
+
+ foundUserCode = true;
+
+ sb.Append ("\tin ");
+
+ if (f.GetFileLineNumber () > 0)
+ sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
+
+ sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
+
bool first = true;
- foreach (object arg in args) {
- if (first)
- first = false;
- else
+ foreach (ParameterInfo pi in mb.GetParameters ()) {
+ if (!first)
sb.Append (", ");
- if (arg == null)
- sb.Append ("null");
- else if (arg is ICollection)
- sb.Append (PrintCollection ((ICollection) arg));
- else
- sb.Append (arg);
+ first = false;
+
+ sb.Append (TypeManager.CSharpName (pi.ParameterType));
}
+ sb.Append (")\n");
}
-
- Console.WriteLine (sb.ToString ());
+
+ return sb.ToString ();
}
- static public string PrintCollection (ICollection collection)
+ public override void Print (AbstractMessage msg)
{
- StringBuilder sb = new StringBuilder ();
+ Print (msg, Console.Error);
+ base.Print (msg);
- sb.Append (collection.GetType ());
- sb.Append ("(");
+ if (Stacktrace)
+ Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
+ }
- bool first = true;
- foreach (object o in collection) {
- if (first)
- first = false;
- else
- sb.Append (", ");
- sb.Append (o);
- }
+ public static string FriendlyStackTrace (Exception e)
+ {
+ return FriendlyStackTrace (new StackTrace (e, true));
+ }
- sb.Append (")");
- return sb.ToString ();
+ public static void StackTrace ()
+ {
+ Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
}
}
regions.Add (new DisableAll (line));
}
- public void WarningDisable (Location location, int code)
+ public void WarningDisable (Location location, int code, Report Report)
{
if (Report.CheckWarningCode (code, location))
regions.Add (new Disable (location.Row, code));
regions.Add (new EnableAll (line));
}
- public void WarningEnable (Location location, int code)
+ public void WarningEnable (Location location, int code, Report Report)
{
if (Report.CheckWarningCode (code, location))
regions.Add (new Enable (location.Row, code));
type_container_resolve_order = new ArrayList ();
EntryPoint = null;
- Report.WarningLevel = 4;
Checked = false;
Unsafe = false;
StdLib = true;
foreach (TypeContainer tc in type_container_resolve_order)
tc.EmitType ();
- if (Report.Errors > 0)
+ if (RootContext.ToplevelTypes.Compiler.Report.Errors > 0)
return;
foreach (TypeContainer tc in type_container_resolve_order)
return fb;
}
- public static void CheckUnsafeOption (Location loc)
+ public static void CheckUnsafeOption (Location loc, Report Report)
{
if (!Unsafe) {
Report.Error (227, loc,
}
}
}
-
-
// TODO: It'd be so nice to have generics
Hashtable anonymous_types;
public ModuleBuilder Builder;
- bool is_unsafe;
+ readonly bool is_unsafe;
+ readonly CompilerContext context;
bool has_default_charset;
static readonly string[] attribute_targets = new string[] { "module" };
- public ModuleContainer (bool isUnsafe)
+ public ModuleContainer (CompilerContext context, bool isUnsafe)
: base (null, null, MemberName.Null, null, Kind.Root)
{
this.is_unsafe = isUnsafe;
+ this.context = context;
+
types = new ArrayList ();
anonymous_types = new Hashtable ();
}
Builder.SetCustomAttribute (cb);
}
+ public override CompilerContext Compiler {
+ get { return context; }
+ }
+
public override void Emit ()
{
if (OptAttributes != null)
OptAttributes.Emit ();
if (is_unsafe) {
- Type t = TypeManager.CoreLookupType ("System.Security", "UnverifiableCodeAttribute", Kind.Class, true);
+ Type t = TypeManager.CoreLookupType (context, "System.Security", "UnverifiableCodeAttribute", Kind.Class, true);
if (t != null) {
ConstructorInfo unverifiable_code_ctor = TypeManager.GetPredefinedConstructor (t, Location.Null, Type.EmptyTypes);
if (unverifiable_code_ctor != null)
get { throw new InternalErrorException ("should not be called"); }
}
+ public override CompilerContext Compiler {
+ get {
+ return PartialContainer.Compiler;
+ }
+ }
+
public override string DocCommentHeader {
get { throw new InternalErrorException ("should not be called"); }
}
//
if (warn)
- Report.Warning (162, 2, loc, "Unreachable code detected");
+ ec.Report.Warning (162, 2, loc, "Unreachable code detected");
ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
bool ok = Resolve (ec);
public virtual Expression CreateExpressionTree (ResolveContext ec)
{
- Report.Error (834, loc, "A lambda expression with statement body cannot be converted to an expresion tree");
+ ec.Report.Error (834, loc, "A lambda expression with statement body cannot be converted to an expresion tree");
return null;
}
Assign ass = expr as Assign;
if (ass != null && ass.Source is Constant) {
- Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
+ ec.Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
}
//
ec.EndFlowBranching ();
if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable && !was_unreachable)
- Report.Warning (162, 2, expr.Location, "Unreachable code detected");
+ ec.Report.Warning (162, 2, expr.Location, "Unreachable code detected");
expr = Expression.ResolveBoolean (ec, expr, loc);
if (expr == null)
protected bool unwind_protect;
protected abstract bool DoResolve (BlockContext ec);
- public virtual void Error_FinallyClause ()
+ public virtual void Error_FinallyClause (Report Report)
{
Report.Error (157, loc, "Control cannot leave the body of a finally clause");
}
if (ec.ReturnType == TypeManager.void_type)
return true;
- Report.Error (126, loc,
+ ec.Report.Error (126, loc,
"An object of a type convertible to `{0}' is required for the return statement",
TypeManager.CSharpName (ec.ReturnType));
return false;
}
if (ec.CurrentBlock.Toplevel.IsIterator) {
- Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
+ ec.Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
"statement to return a value, or yield break to end the iteration");
}
AnonymousExpression am = ec.CurrentAnonymousMethod;
if (am == null && ec.ReturnType == TypeManager.void_type) {
- Report.Error (127, loc, "`{0}': A return keyword must not be followed by any expression when method returns void",
+ ec.Report.Error (127, loc, "`{0}': A return keyword must not be followed by any expression when method returns void",
ec.GetSignatureForError ());
}
if (Expr == null) {
if (am != null) {
- Report.Error (1662, loc,
+ ec.Report.Error (1662, loc,
"Cannot convert `{0}' to delegate type `{1}' because some of the return types in the block are not implicitly convertible to the delegate return type",
am.ContainerType, am.GetSignatureForError ());
}
public override bool Resolve (BlockContext ec)
{
- int errors = Report.Errors;
unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
ec.CurrentBranching.CurrentUsageVector.Goto ();
- return errors == Report.Errors;
+ return true;
}
public Goto (string label, Location l)
ec.CurrentBranching.CurrentUsageVector.Goto ();
if (ec.Switch == null) {
- Report.Error (153, loc, "A goto case is only valid inside a switch statement");
+ ec.Report.Error (153, loc, "A goto case is only valid inside a switch statement");
return false;
}
if (!ec.Switch.GotDefault) {
- FlowBranchingBlock.Error_UnknownLabel (loc, "default");
+ FlowBranchingBlock.Error_UnknownLabel (loc, "default", ec.Report);
return false;
}
public override bool Resolve (BlockContext ec)
{
if (ec.Switch == null){
- Report.Error (153, loc, "A goto case is only valid inside a switch statement");
+ ec.Report.Error (153, loc, "A goto case is only valid inside a switch statement");
return false;
}
Constant c = expr as Constant;
if (c == null) {
- Report.Error (150, expr.Location, "A constant value is expected");
+ ec.Report.Error (150, expr.Location, "A constant value is expected");
return false;
}
}
if (!Convert.ImplicitStandardConversionExists (c, type))
- Report.Warning (469, 2, loc,
+ ec.Report.Warning (469, 2, loc,
"The `goto case' value is not implicitly convertible to type `{0}'",
TypeManager.CSharpName (type));
if (sl == null){
FlowBranchingBlock.Error_UnknownLabel (loc, "case " +
- (c.GetValue () == null ? "null" : val.ToString ()));
+ (c.GetValue () == null ? "null" : val.ToString ()), ec.Report);
return false;
}
if (Convert.ImplicitConversionExists (ec, expr, TypeManager.exception_type))
expr = Convert.ImplicitConversion (ec, expr, TypeManager.exception_type, loc);
else
- Report.Error (155, expr.Location, "The type caught or thrown must be derived from System.Exception");
+ ec.Report.Error (155, expr.Location, "The type caught or thrown must be derived from System.Exception");
return true;
}
public override bool Resolve (BlockContext ec)
{
- int errors = Report.Errors;
unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
ec.CurrentBranching.CurrentUsageVector.Goto ();
- return errors == Report.Errors;
+ return true;
}
protected override void DoEmit (EmitContext ec)
public override bool Resolve (BlockContext ec)
{
- int errors = Report.Errors;
unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
ec.CurrentBranching.CurrentUsageVector.Goto ();
- return errors == Report.Errors;
+ return true;
}
protected override void DoEmit (EmitContext ec)
if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
return true;
- return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, block.StartLocation);
+ return VariableInfo.TypeInfo.IsFullyInitialized (ec, VariableInfo, block.StartLocation);
}
public bool IsAssigned (BlockContext ec)
return true;
if (VariableType.IsAbstract && VariableType.IsSealed) {
- FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType);
+ FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType, ec.Report);
return false;
}
if (VariableType.IsPointer && !ec.IsUnsafe)
- Expression.UnsafeError (Location);
+ Expression.UnsafeError (ec, Location);
return true;
}
EndLocation = loc;
}
- protected static void Error_158 (string name, Location loc)
+ protected void Error_158 (string name, Location loc)
{
- Report.Error (158, loc, "The label `{0}' shadows another label " +
+ Toplevel.Report.Error (158, loc, "The label `{0}' shadows another label " +
"by the same name in a contained scope", name);
}
while (cur != null) {
LabeledStatement s = cur.DoLookupLabel (name);
if (s != null) {
- Report.SymbolRelatedToPreviousError (s.loc, s.Name);
- Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
+ Toplevel.Report.SymbolRelatedToPreviousError (s.loc, s.Name);
+ Toplevel.Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
return false;
}
if (s == null)
continue;
- Report.SymbolRelatedToPreviousError (s.loc, s.Name);
+ Toplevel.Report.SymbolRelatedToPreviousError (s.loc, s.Name);
Error_158 (name, target.loc);
return false;
}
// block, we violate the invariant meaning in a block.
//
if (b == this) {
- Report.SymbolRelatedToPreviousError (kvi.Location, name);
- Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
+ Toplevel.Report.SymbolRelatedToPreviousError (kvi.Location, name);
+ Toplevel.Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
return false;
}
return true;
if (this is ToplevelBlock) {
- Report.SymbolRelatedToPreviousError (kvi.Location, name);
- e.Error_VariableIsUsedBeforeItIsDeclared (name);
+ Toplevel.Report.SymbolRelatedToPreviousError (kvi.Location, name);
+ e.Error_VariableIsUsedBeforeItIsDeclared (Toplevel.Report, name);
return false;
}
// Even though we detected the error when the name is used, we
// treat it as if the variable declaration was in error.
//
- Report.SymbolRelatedToPreviousError (loc, name);
+ Toplevel.Report.SymbolRelatedToPreviousError (loc, name);
Error_AlreadyDeclared (kvi.Location, name, "parent or current");
return false;
}
{
LocalInfo vi = GetLocalInfo (name);
if (vi != null) {
- Report.SymbolRelatedToPreviousError (vi.Location, name);
+ block.Report.SymbolRelatedToPreviousError (vi.Location, name);
if (Explicit == vi.Block.Explicit) {
Error_AlreadyDeclared (l, name, null);
} else {
if (Toplevel.GenericMethod != null) {
foreach (TypeParameter tp in Toplevel.GenericMethod.CurrentTypeParameters) {
if (tp.Name == name) {
- Report.SymbolRelatedToPreviousError (tp);
- Error_AlreadyDeclaredTypeParameter (loc, name, "local variable");
+ Toplevel.Report.SymbolRelatedToPreviousError (tp);
+ Error_AlreadyDeclaredTypeParameter (Toplevel.Report, loc, name, "local variable");
return null;
}
}
IKnownVariable kvi = Explicit.GetKnownVariable (name);
if (kvi != null) {
- Report.SymbolRelatedToPreviousError (kvi.Location, name);
+ Toplevel.Report.SymbolRelatedToPreviousError (kvi.Location, name);
Error_AlreadyDeclared (l, name, "child");
return null;
}
return;
}
- Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
+ Toplevel.Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
"in this scope because it would give a different meaning " +
"to `{0}', which is already used in a `{1}' scope " +
"to denote something else", var, reason);
protected virtual void Error_AlreadyDeclared (Location loc, string name)
{
- Report.Error (128, loc,
+ Toplevel.Report.Error (128, loc,
"A local variable named `{0}' is already defined in this scope", name);
}
- public virtual void Error_AlreadyDeclaredTypeParameter (Location loc, string name, string conflict)
+ public virtual void Error_AlreadyDeclaredTypeParameter (Report r, Location loc, string name, string conflict)
{
- Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
+ r.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
name, conflict);
}
if (variable_type == null) {
if (vi.Type is VarExpr)
- Report.Error (822, vi.Type.Location, "An implicitly typed local variable cannot be a constant");
+ ec.Report.Error (822, vi.Type.Location, "An implicitly typed local variable cannot be a constant");
continue;
}
constants.Remove (name);
if (!Const.IsConstantTypeValid (variable_type)) {
- Const.Error_InvalidConstantType (variable_type, loc);
+ Const.Error_InvalidConstantType (variable_type, loc, ec.Report);
continue;
}
Constant ce = e as Constant;
if (ce == null) {
- Const.Error_ExpressionMustBeConstant (vi.Location, name);
+ Const.Error_ExpressionMustBeConstant (vi.Location, name, ec.Report);
continue;
}
e = ce.ConvertImplicitly (variable_type);
if (e == null) {
if (TypeManager.IsReferenceType (variable_type))
- Const.Error_ConstantCanBeInitializedWithNullOnly (variable_type, vi.Location, vi.Name);
+ Const.Error_ConstantCanBeInitializedWithNullOnly (variable_type, vi.Location, vi.Name, ec.Report);
else
ce.Error_ValueCannotBeConverted (ec, vi.Location, variable_type, false);
continue;
}
}
- void UsageWarning ()
+ void UsageWarning (BlockContext ec)
{
- if (variables == null || Report.WarningLevel < 3)
+ if (variables == null || ec.Report.WarningLevel < 3)
return;
foreach (DictionaryEntry de in variables) {
// vi.VariableInfo can be null for 'catch' variables
if (vi.VariableInfo != null && vi.VariableInfo.IsEverAssigned)
- Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
+ ec.Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
else
- Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
+ ec.Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
}
}
}
- static void CheckPossibleMistakenEmptyStatement (Statement s)
+ static void CheckPossibleMistakenEmptyStatement (BlockContext ec, Statement s)
{
Statement body;
return;
if (body == null || body is EmptyStatement)
- Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
+ ec.Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
}
public override bool Resolve (BlockContext ec)
Block prev_block = ec.CurrentBlock;
bool ok = true;
- int errors = Report.Errors;
+ int errors = ec.Report.Errors;
ec.CurrentBlock = this;
ec.StartFlowBranching (this);
for (int ix = 0; ix < statement_count; ix++){
Statement s = (Statement) statements [ix];
// Check possible empty statement (CS0642)
- if (Report.WarningLevel >= 3 &&
- ix + 1 < statement_count &&
- statements [ix + 1] is ExplicitBlock)
- CheckPossibleMistakenEmptyStatement (s);
+ if (ix + 1 < statement_count && ec.Report.WarningLevel >= 3 &&
+ statements [ix + 1] is ExplicitBlock)
+ CheckPossibleMistakenEmptyStatement (ec, s);
//
// Warn if we detect unreachable code.
continue;
if (!unreachable_shown && !(s is LabeledStatement)) {
- Report.Warning (162, 2, s.loc, "Unreachable code detected");
+ ec.Report.Warning (162, 2, s.loc, "Unreachable code detected");
unreachable_shown = true;
}
if (this == Toplevel && !Toplevel.IsThisAssigned (ec) && !flow_unreachable)
ok = false;
- if ((labels != null) && (Report.WarningLevel >= 2)) {
+ if ((labels != null) && (ec.Report.WarningLevel >= 2)) {
foreach (LabeledStatement label in labels.Values)
if (!label.HasBeenReferenced)
- Report.Warning (164, 2, label.loc, "This label has not been referenced");
+ ec.Report.Warning (164, 2, label.loc, "This label has not been referenced");
}
- if (ok && errors == Report.Errors)
- UsageWarning ();
+ if (ok && errors == ec.Report.Errors)
+ UsageWarning (ec);
return ok;
}
unreachable = true;
if (warn)
- Report.Warning (162, 2, loc, "Unreachable code detected");
+ ec.Report.Warning (162, 2, loc, "Unreachable code detected");
ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
bool ok = Resolve (ec);
LocalInfo this_variable;
bool resolved;
bool unreachable;
+ CompilerContext compiler;
public HoistedVariable HoistedThisVariable;
get { return parameters; }
}
+ public Report Report {
+ get { return compiler.Report; }
+ }
+
public GenericMethod GenericMethod {
get { return generic; }
}
get { return Parent == null ? null : Parent.Toplevel; }
}
- public ToplevelBlock (Block parent, ParametersCompiled parameters, Location start) :
- this (parent, (Flags) 0, parameters, start)
+ public ToplevelBlock (CompilerContext ctx, Block parent, ParametersCompiled parameters, Location start) :
+ this (ctx, parent, (Flags) 0, parameters, start)
{
}
- public ToplevelBlock (Block parent, ParametersCompiled parameters, GenericMethod generic, Location start) :
- this (parent, parameters, start)
+ public ToplevelBlock (CompilerContext ctx, Block parent, ParametersCompiled parameters, GenericMethod generic, Location start) :
+ this (ctx, parent, parameters, start)
{
this.generic = generic;
}
-
- public ToplevelBlock (ParametersCompiled parameters, Location start) :
- this (null, (Flags) 0, parameters, start)
+
+ public ToplevelBlock (CompilerContext ctx, ParametersCompiled parameters, Location start) :
+ this (ctx, null, (Flags) 0, parameters, start)
{
}
- ToplevelBlock (Flags flags, ParametersCompiled parameters, Location start) :
- this (null, flags, parameters, start)
+ ToplevelBlock (CompilerContext ctx, Flags flags, ParametersCompiled parameters, Location start) :
+ this (ctx, null, flags, parameters, start)
{
}
// We use 'Parent' to hook up to the containing block, but don't want to register the current block as a child.
// So, we use a two-stage setup -- first pass a null parent to the base constructor, and then override 'Parent'.
- public ToplevelBlock (Block parent, Flags flags, ParametersCompiled parameters, Location start) :
+ public ToplevelBlock (CompilerContext ctx, Block parent, Flags flags, ParametersCompiled parameters, Location start) :
base (null, flags, start, Location.Null)
{
+ this.compiler = ctx;
this.Toplevel = this;
this.parameters = parameters;
ProcessParameters ();
}
- public ToplevelBlock (Location loc)
- : this (null, (Flags) 0, ParametersCompiled.EmptyReadOnlyParameters, loc)
+ public ToplevelBlock (CompilerContext ctx, Location loc)
+ : this (ctx, null, (Flags) 0, ParametersCompiled.EmptyReadOnlyParameters, loc)
{
}
} catch (Exception) {
#if PRODUCTION
if (rc.CurrentBlock != null) {
- Report.Error (584, rc.CurrentBlock.StartLocation, "Internal compiler error: Phase Resolve");
+ ec.Report.Error (584, rc.CurrentBlock.StartLocation, "Internal compiler error: Phase Resolve");
} else {
- Report.Error (587, "Internal compiler error: Phase Resolve");
+ ec.Report.Error (587, "Internal compiler error: Phase Resolve");
}
#endif
throw;
if (rc.ReturnType != TypeManager.void_type && !unreachable) {
if (rc.CurrentAnonymousMethod == null) {
- Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
+ rc.Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
return false;
} else if (!rc.CurrentAnonymousMethod.IsIterator) {
- Report.Error (1643, rc.CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
+ rc.Report.Error (1643, rc.CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
rc.CurrentAnonymousMethod.GetSignatureForError ());
return false;
}
bool ResolveMeta (BlockContext ec, ParametersCompiled ip)
{
- int errors = Report.Errors;
+ int errors = ec.Report.Errors;
int orig_count = parameters.Count;
if (ip != null)
ResolveMeta (ec, offset);
- return Report.Errors == errors;
+ return ec.Report.Errors == errors;
}
// <summary>
Constant c = e as Constant;
if (c == null){
- Report.Error (150, loc, "A constant value is expected");
+ ec.Report.Error (150, loc, "A constant value is expected");
return false;
}
return true;
}
- public void Error_AlreadyOccurs (Type switch_type, SwitchLabel collision_with)
+ public void Error_AlreadyOccurs (ResolveContext ec, Type switch_type, SwitchLabel collision_with)
{
string label;
if (converted == null)
else
label = converted.ToString ();
- Report.SymbolRelatedToPreviousError (collision_with.loc, null);
- Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
+ ec.Report.SymbolRelatedToPreviousError (collision_with.loc, null);
+ ec.Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
}
public SwitchLabel Clone (CloneContext clonectx)
continue;
if (converted != null){
- Report.ExtraInformation (loc, "(Ambiguous implicit user defined conversion in previous ");
+ ec.Report.ExtraInformation (loc, "(Ambiguous implicit user defined conversion in previous ");
return null;
}
foreach (SwitchLabel sl in ss.Labels){
if (sl.Label == null){
if (default_section != null){
- sl.Error_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
+ sl.Error_AlreadyOccurs (ec, SwitchType, (SwitchLabel)default_section.Labels [0]);
error = true;
}
default_section = ss;
try {
Elements.Add (key, sl);
} catch (ArgumentException) {
- sl.Error_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
+ sl.Error_AlreadyOccurs (ec, SwitchType, (SwitchLabel)Elements [key]);
error = true;
}
}
}
if (new_expr == null){
- Report.Error (151, loc,
+ ec.Report.Error (151, loc,
"A switch expression of type `{0}' cannot be converted to an integral type, bool, char, string, enum or nullable type",
TypeManager.CSharpName (Expr.Type));
return false;
SwitchType = new_expr.Type;
if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
- Report.FeatureIsNotAvailable (loc, "switch expression of boolean type");
+ ec.Report.FeatureIsNotAvailable (loc, "switch expression of boolean type");
return false;
}
return false;
if (!TypeManager.IsReferenceType (expr.Type)){
- Report.Error (185, loc,
+ ec.Report.Error (185, loc,
"`{0}' is not a reference type as required by the lock statement",
TypeManager.CSharpName (expr.Type));
return false;
temp.Resolve (ec);
if (TypeManager.void_monitor_enter_object == null || TypeManager.void_monitor_exit_object == null) {
- Type monitor_type = TypeManager.CoreLookupType ("System.Threading", "Monitor", Kind.Class, true);
+ Type monitor_type = TypeManager.CoreLookupType (ec.Compiler, "System.Threading", "Monitor", Kind.Class, true);
TypeManager.void_monitor_enter_object = TypeManager.GetPredefinedMethod (
monitor_type, "Enter", loc, TypeManager.object_type);
TypeManager.void_monitor_exit_object = TypeManager.GetPredefinedMethod (
public override bool Resolve (BlockContext ec)
{
if (ec.CurrentIterator != null)
- Report.Error (1629, loc, "Unsafe code may not appear in iterators");
+ ec.Report.Error (1629, loc, "Unsafe code may not appear in iterators");
using (ec.Set (ResolveContext.Options.UnsafeScope))
return Block.Resolve (ec);
public override bool Resolve (BlockContext ec)
{
if (!ec.IsUnsafe){
- Expression.UnsafeError (loc);
+ Expression.UnsafeError (ec, loc);
return false;
}
TypeExpr texpr = type.ResolveAsContextualType (ec, false);
if (texpr == null) {
if (type is VarExpr)
- Report.Error (821, type.Location, "A fixed statement cannot use an implicitly typed local variable");
+ ec.Report.Error (821, type.Location, "A fixed statement cannot use an implicitly typed local variable");
return false;
}
data = new Emitter [declarators.Count];
if (!expr_type.IsPointer){
- Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
+ ec.Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
return false;
}
//
if (e is Cast){
- Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
+ ec.Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
return false;
}
}
if (data [i++] == null)
- Report.Error (213, vi.Location, "You cannot use the fixed statement to take the address of an already fixed expression");
+ ec.Report.Error (213, vi.Location, "You cannot use the fixed statement to take the address of an already fixed expression");
e = Convert.ImplicitConversionRequired (ec, e, expr_type, loc);
}
type = te.Type;
if (type != TypeManager.exception_type && !TypeManager.IsSubclassOf (type, TypeManager.exception_type)){
- Report.Error (155, loc, "The type caught or thrown must be derived from System.Exception");
+ ec.Report.Error (155, loc, "The type caught or thrown must be derived from System.Exception");
return false;
}
} else
Type resolved_type = c.CatchType;
for (int ii = 0; ii < last_index; ++ii) {
if (resolved_type == prev_catches [ii] || TypeManager.IsSubclassOf (resolved_type, prev_catches [ii])) {
- Report.Error (160, c.loc,
+ ec.Report.Error (160, c.loc,
"A previous catch clause already catches all exceptions of this or a super type `{0}'",
TypeManager.CSharpName (prev_catches [ii]));
ok = false;
if (CodeGen.Assembly.WrapNonExceptionThrows) {
foreach (Catch c in Specific){
if (c.CatchType == TypeManager.exception_type && PredefinedAttributes.Get.RuntimeCompatibility.IsDefined) {
- Report.Warning (1058, 1, c.loc, "A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
+ ec.Report.Warning (1058, 1, c.loc, "A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
}
}
}
if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)) {
if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
- Using.Error_IsNotConvertibleToIDisposable (expr);
+ Using.Error_IsNotConvertibleToIDisposable (ec, expr);
return false;
}
}
return;
}
- Expression ml = Expression.MemberLookup (
+ Expression ml = Expression.MemberLookup (RootContext.ToplevelTypes.Compiler,
ec.CurrentType, TypeManager.idisposable_type, expr_type,
"Dispose", Location.Null);
}
if (mi == null) {
- Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
+ RootContext.ToplevelTypes.Compiler.Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
return;
}
loc = l;
}
- static public void Error_IsNotConvertibleToIDisposable (Expression expr)
+ static public void Error_IsNotConvertibleToIDisposable (BlockContext ec, Expression expr)
{
- Report.SymbolRelatedToPreviousError (expr.Type);
- Report.Error (1674, expr.Location, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
+ ec.Report.SymbolRelatedToPreviousError (expr.Type);
+ ec.Report.Error (1674, expr.Location, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
expr.GetSignatureForError ());
}
Expression e = Convert.ImplicitConversionStandard (ec, assign, TypeManager.idisposable_type, var.Location);
if (e == null) {
- Error_IsNotConvertibleToIDisposable (var);
+ Error_IsNotConvertibleToIDisposable (ec, var);
return false;
}
//
if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
- Report.Error (202, loc, "foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
+ ec.Report.Error (202, loc, "foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
return false;
}
//
bool FetchGetCurrent (ResolveContext ec, Type t)
{
- PropertyExpr pe = Expression.MemberLookup (
+ PropertyExpr pe = Expression.MemberLookup (ec.Compiler,
ec.CurrentType, t, "Current", MemberTypes.Property,
Expression.AllBindingFlags, loc) as PropertyExpr;
if (pe == null)
return true;
}
- void Error_Enumerator ()
+ void Error_Enumerator (BlockContext ec)
{
if (enumerator_found) {
return;
}
- Report.Error (1579, loc,
+ ec.Report.Error (1579, loc,
"foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
TypeManager.CSharpName (expr.Type));
}
bool TryType (ResolveContext ec, Type t)
{
- MethodGroupExpr mg = Expression.MemberLookup (
+ MethodGroupExpr mg = Expression.MemberLookup (ec.Compiler,
ec.CurrentType, t, "GetEnumerator", MemberTypes.Method,
Expression.AllBindingFlags, loc) as MethodGroupExpr;
if (mg == null)
continue;
MethodBase mb = TypeManager.DropGenericMethodArguments (mi);
- Report.SymbolRelatedToPreviousError (t);
- Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
+ ec.Report.SymbolRelatedToPreviousError (t);
+ ec.Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
"because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
TypeManager.CSharpName (t), TypeManager.CSharpSignature (mb));
return false;
TypeManager.ImplementsInterface (result.DeclaringType, mi.DeclaringType))
continue;
- Report.SymbolRelatedToPreviousError (result);
- Report.SymbolRelatedToPreviousError (mi);
- Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
+ ec.Report.SymbolRelatedToPreviousError (result);
+ ec.Report.SymbolRelatedToPreviousError (mi);
+ ec.Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
return false;
}
bool ProbeCollectionType (ResolveContext ec, Type t)
{
- int errors = Report.Errors;
+ int errors = ec.Report.Errors;
for (Type tt = t; tt != null && tt != TypeManager.object_type;){
if (TryType (ec, tt))
return true;
tt = tt.BaseType;
}
- if (Report.Errors > errors)
+ if (ec.Report.Errors > errors)
return false;
//
enumerator_type = TypeManager.ienumerator_type;
if (!ProbeCollectionType (ec, expr.Type)) {
- Error_Enumerator ();
+ Error_Enumerator (ec);
return false;
}
return false;
if (expr.IsNull) {
- Report.Error (186, loc, "Use of null is not valid in this context");
+ ec.Report.Error (186, loc, "Use of null is not valid in this context");
return false;
}
statement = new ArrayForeach (this, expr.Type.GetArrayRank ());
} else {
if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
- Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
+ ec.Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
expr.ExprClassName);
return false;
}
}
}
-#if NET_4_0
+#if NET_4_0 || MS_COMPATIBLE
[System.Diagnostics.DebuggerDisplay ("Dynamic type")]
#endif
class DynamicType : Type
}
}
- public static bool NamespaceClash (string name, Location loc)
- {
- if (!GlobalRootNamespace.Instance.IsNamespace (name))
- return false;
-
- Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
- return true;
- }
-
/// <summary>
/// Returns the C# name of a type if possible, or the full type name otherwise
/// </summary>
// Looks up a type, and aborts if it is not found. This is used
// by predefined types required by the compiler
//
- public static Type CoreLookupType (string ns_name, string name, Kind type_kind, bool required)
+ public static Type CoreLookupType (CompilerContext ctx, string ns_name, string name, Kind type_kind, bool required)
{
Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, true);
- Expression expr = ns.Lookup (name, Location.Null);
+ Expression expr = ns.Lookup (ctx, name, Location.Null);
if (expr == null) {
if (required) {
- Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
+ ctx.Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
ns_name, name);
}
return null;
return t;
}
- Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
+ ctx.Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
ns_name, name);
return null;
}
if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
method_args = "(" + TypeManager.CSharpName (args) + ")";
- Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
+ RootContext.ToplevelTypes.Compiler.Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
TypeManager.CSharpName (t), name, method_args);
return null;
/// population of the type has happened (for example, to
/// bootstrap the corlib.dll
/// </remarks>
- public static bool InitCoreTypes ()
+ public static bool InitCoreTypes (CompilerContext ctx)
{
- object_type = CoreLookupType ("System", "Object", Kind.Class, true);
+ object_type = CoreLookupType (ctx, "System", "Object", Kind.Class, true);
system_object_expr.Type = object_type;
- value_type = CoreLookupType ("System", "ValueType", Kind.Class, true);
+ value_type = CoreLookupType (ctx, "System", "ValueType", Kind.Class, true);
system_valuetype_expr.Type = value_type;
- attribute_type = CoreLookupType ("System", "Attribute", Kind.Class, true);
+ attribute_type = CoreLookupType (ctx, "System", "Attribute", Kind.Class, true);
- int32_type = CoreLookupType ("System", "Int32", Kind.Struct, true);
+ int32_type = CoreLookupType (ctx, "System", "Int32", Kind.Struct, true);
system_int32_expr.Type = int32_type;
- int64_type = CoreLookupType ("System", "Int64", Kind.Struct, true);
+ int64_type = CoreLookupType (ctx, "System", "Int64", Kind.Struct, true);
system_int64_expr.Type = int64_type;
- uint32_type = CoreLookupType ("System", "UInt32", Kind.Struct, true);
+ uint32_type = CoreLookupType (ctx, "System", "UInt32", Kind.Struct, true);
system_uint32_expr.Type = uint32_type;
- uint64_type = CoreLookupType ("System", "UInt64", Kind.Struct, true);
+ uint64_type = CoreLookupType (ctx, "System", "UInt64", Kind.Struct, true);
system_uint64_expr.Type = uint64_type;
- byte_type = CoreLookupType ("System", "Byte", Kind.Struct, true);
+ byte_type = CoreLookupType (ctx, "System", "Byte", Kind.Struct, true);
system_byte_expr.Type = byte_type;
- sbyte_type = CoreLookupType ("System", "SByte", Kind.Struct, true);
+ sbyte_type = CoreLookupType (ctx, "System", "SByte", Kind.Struct, true);
system_sbyte_expr.Type = sbyte_type;
- short_type = CoreLookupType ("System", "Int16", Kind.Struct, true);
+ short_type = CoreLookupType (ctx, "System", "Int16", Kind.Struct, true);
system_int16_expr.Type = short_type;
- ushort_type = CoreLookupType ("System", "UInt16", Kind.Struct, true);
+ ushort_type = CoreLookupType (ctx, "System", "UInt16", Kind.Struct, true);
system_uint16_expr.Type = ushort_type;
- ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator", Kind.Interface, true);
- ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable", Kind.Interface, true);
- idisposable_type = CoreLookupType ("System", "IDisposable", Kind.Interface, true);
+ ienumerator_type = CoreLookupType (ctx, "System.Collections", "IEnumerator", Kind.Interface, true);
+ ienumerable_type = CoreLookupType (ctx, "System.Collections", "IEnumerable", Kind.Interface, true);
+ idisposable_type = CoreLookupType (ctx, "System", "IDisposable", Kind.Interface, true);
// HACK: DefineType immediately resolves iterators (very wrong)
- generic_ienumerator_type = CoreLookupType ("System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
+ generic_ienumerator_type = CoreLookupType (ctx, "System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
- char_type = CoreLookupType ("System", "Char", Kind.Struct, true);
+ char_type = CoreLookupType (ctx, "System", "Char", Kind.Struct, true);
system_char_expr.Type = char_type;
- string_type = CoreLookupType ("System", "String", Kind.Class, true);
+ string_type = CoreLookupType (ctx, "System", "String", Kind.Class, true);
system_string_expr.Type = string_type;
- float_type = CoreLookupType ("System", "Single", Kind.Struct, true);
+ float_type = CoreLookupType (ctx, "System", "Single", Kind.Struct, true);
system_single_expr.Type = float_type;
- double_type = CoreLookupType ("System", "Double", Kind.Struct, true);
+ double_type = CoreLookupType (ctx, "System", "Double", Kind.Struct, true);
system_double_expr.Type = double_type;
- decimal_type = CoreLookupType ("System", "Decimal", Kind.Struct, true);
+ decimal_type = CoreLookupType (ctx, "System", "Decimal", Kind.Struct, true);
system_decimal_expr.Type = decimal_type;
- bool_type = CoreLookupType ("System", "Boolean", Kind.Struct, true);
+ bool_type = CoreLookupType (ctx, "System", "Boolean", Kind.Struct, true);
system_boolean_expr.Type = bool_type;
- intptr_type = CoreLookupType ("System", "IntPtr", Kind.Struct, true);
+ intptr_type = CoreLookupType (ctx, "System", "IntPtr", Kind.Struct, true);
system_intptr_expr.Type = intptr_type;
- uintptr_type = CoreLookupType ("System", "UIntPtr", Kind.Struct, true);
+ uintptr_type = CoreLookupType (ctx, "System", "UIntPtr", Kind.Struct, true);
- multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate", Kind.Class, true);
- delegate_type = CoreLookupType ("System", "Delegate", Kind.Class, true);
+ multicast_delegate_type = CoreLookupType (ctx, "System", "MulticastDelegate", Kind.Class, true);
+ delegate_type = CoreLookupType (ctx, "System", "Delegate", Kind.Class, true);
- enum_type = CoreLookupType ("System", "Enum", Kind.Class, true);
- array_type = CoreLookupType ("System", "Array", Kind.Class, true);
- void_type = CoreLookupType ("System", "Void", Kind.Struct, true);
+ enum_type = CoreLookupType (ctx, "System", "Enum", Kind.Class, true);
+ array_type = CoreLookupType (ctx, "System", "Array", Kind.Class, true);
+ void_type = CoreLookupType (ctx, "System", "Void", Kind.Struct, true);
system_void_expr.Type = void_type;
- type_type = CoreLookupType ("System", "Type", Kind.Class, true);
- exception_type = CoreLookupType ("System", "Exception", Kind.Class, true);
+ type_type = CoreLookupType (ctx, "System", "Type", Kind.Class, true);
+ exception_type = CoreLookupType (ctx, "System", "Exception", Kind.Class, true);
- runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle", Kind.Struct, true);
- runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle", Kind.Struct, true);
+ runtime_field_handle_type = CoreLookupType (ctx, "System", "RuntimeFieldHandle", Kind.Struct, true);
+ runtime_handle_type = CoreLookupType (ctx, "System", "RuntimeTypeHandle", Kind.Struct, true);
PredefinedAttributes.Get.ParamArray.Resolve (false);
PredefinedAttributes.Get.Out.Resolve (false);
- return Report.Errors == 0;
+ return ctx.Report.Errors == 0;
}
//
// Initializes optional core types
//
- public static void InitOptionalCoreTypes ()
+ public static void InitOptionalCoreTypes (CompilerContext ctx)
{
//
// These are only used for compare purposes
//
PredefinedAttributes.Get.Initialize ();
- runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle", Kind.Struct, false);
- asynccallback_type = CoreLookupType ("System", "AsyncCallback", Kind.Delegate, false);
- iasyncresult_type = CoreLookupType ("System", "IAsyncResult", Kind.Interface, false);
- typed_reference_type = CoreLookupType ("System", "TypedReference", Kind.Struct, false);
- arg_iterator_type = CoreLookupType ("System", "ArgIterator", Kind.Struct, false);
- mbr_type = CoreLookupType ("System", "MarshalByRefObject", Kind.Class, false);
+ runtime_argument_handle_type = CoreLookupType (ctx, "System", "RuntimeArgumentHandle", Kind.Struct, false);
+ asynccallback_type = CoreLookupType (ctx, "System", "AsyncCallback", Kind.Delegate, false);
+ iasyncresult_type = CoreLookupType (ctx, "System", "IAsyncResult", Kind.Interface, false);
+ typed_reference_type = CoreLookupType (ctx, "System", "TypedReference", Kind.Struct, false);
+ arg_iterator_type = CoreLookupType (ctx, "System", "ArgIterator", Kind.Struct, false);
+ mbr_type = CoreLookupType (ctx, "System", "MarshalByRefObject", Kind.Class, false);
//
// Optional attributes, used for error reporting only
// c.Define ();
//}
- generic_ilist_type = CoreLookupType ("System.Collections.Generic", "IList`1", Kind.Interface, false);
- generic_icollection_type = CoreLookupType ("System.Collections.Generic", "ICollection`1", Kind.Interface, false);
- generic_ienumerable_type = CoreLookupType ("System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
- generic_nullable_type = CoreLookupType ("System", "Nullable`1", Kind.Struct, false);
+ generic_ilist_type = CoreLookupType (ctx, "System.Collections.Generic", "IList`1", Kind.Interface, false);
+ generic_icollection_type = CoreLookupType (ctx, "System.Collections.Generic", "ICollection`1", Kind.Interface, false);
+ generic_ienumerable_type = CoreLookupType (ctx, "System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
+ generic_nullable_type = CoreLookupType (ctx, "System", "Nullable`1", Kind.Struct, false);
//
// Optional types which are used as types and for member lookup
//
- runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
+ runtime_helpers_type = CoreLookupType (ctx, "System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
// New in .NET 3.5
// Note: extension_attribute_type is already loaded
- expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", Kind.Class, false);
+ expression_type = CoreLookupType (ctx, "System.Linq.Expressions", "Expression`1", Kind.Class, false);
if (!RootContext.StdLib) {
//
set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
} else {
- Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
+ ctx.Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
TypeManager.CSharpName (system_4_type_arg));
}
if (key_token != null) {
if (this_token.Length == 0) {
// Same name, but assembly is not strongnamed
- Error_FriendAccessNameNotMatching (aname.FullName);
+ Error_FriendAccessNameNotMatching (aname.FullName, RootContext.ToplevelTypes.Compiler.Report);
break;
}
return true;
}
- static void Error_FriendAccessNameNotMatching (string other_name)
+ static void Error_FriendAccessNameNotMatching (string other_name, Report Report)
{
Report.Error (281,
"Friend access was granted to `{0}', but the output assembly is named `{1}'. Try adding a reference to `{0}' or change the output assembly name to match it",
return pd;
}
- public static AParametersCollection GetDelegateParameters (Type t)
+ public static AParametersCollection GetDelegateParameters (ResolveContext ec, Type t)
{
Delegate d = builder_to_declspace [t] as Delegate;
if (d != null)
return d.Parameters;
- MethodInfo invoke_mb = Delegate.GetInvokeMethod (t, t);
+ MethodInfo invoke_mb = Delegate.GetInvokeMethod (ec.Compiler, t, t);
return GetParameterData (invoke_mb);
}
continue;
if (hash.Contains (ftc)) {
- Report.Error (523, tc.Location,
+ RootContext.ToplevelTypes.Compiler.Report.Error (523, tc.Location,
"Struct member `{0}.{1}' of type `{2}' " +
"causes a cycle in the struct layout",
tc.Name, field.Name, ftc.Name);
while (t.IsPointer)
t = GetElementType (t);
- Report.SymbolRelatedToPreviousError (t);
- Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
+ RootContext.ToplevelTypes.Compiler.Report.SymbolRelatedToPreviousError (t);
+ RootContext.ToplevelTypes.Compiler.Report.Error (208, loc,
+ "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
CSharpName (t));
return false;
new Type [] { typeof (Type), typeof (bool)},
null);
if (declare_local_method == null){
- Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
+ RootContext.ToplevelTypes.Compiler.Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
return ig.DeclareLocal (t);
}
}