Skip to content

Commit

Permalink
Refactoring: clean code, replace assert2 with assert.
Browse files Browse the repository at this point in the history
  • Loading branch information
VladD2 committed Mar 9, 2017
1 parent 143e20f commit eda468f
Show file tree
Hide file tree
Showing 82 changed files with 110 additions and 296 deletions.
2 changes: 1 addition & 1 deletion Linq/Macro/QueryClause.n
Expand Up @@ -69,7 +69,7 @@ namespace Nemerle.Linq
{
def make_x_param(parms : SCG.List[PExpr]) : PExpr
{
assert2(!parms.IsEmpty());
assert(!parms.IsEmpty());
if (parms.Count == 1) parms[0] else PExpr.Tuple(NList.ToList(parms), 1)
}
def appendArgToTuple(paramExpr, exprForAppend) : PExpr.Tuple
Expand Down
32 changes: 7 additions & 25 deletions Linq/Macro/ToExpressionImpl.n
@@ -1,4 +1,4 @@
using System;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
Expand Down Expand Up @@ -40,7 +40,6 @@ namespace Nemerle.Linq

Error(expr : TExpr, msg : string = null) : PExpr
{
//assert2(false, "fail convertion to 'expression tree'");
def text =
if (msg == null)
$"conversion from $(expr.GetType().Name) (expr: $expr) into 'expression tree' not supported"
Expand Down Expand Up @@ -75,7 +74,7 @@ namespace Nemerle.Linq
| StaticRef(from, field is IField, []) => <[ Expression.Field(null, $(PExpr.Typed(TExpr.FieldOf(from, field))) : FieldInfo) ]>
| DefValIn (name, init, body) => ConvertMemberInit(lparms, name, init, body)
| DefaultValue as expr => <[ Expression.Default(typeof($(expr.Type : typed))) ]>
| unsupported => assert2(false, "fail convertion to 'expression tree'"); Error(unsupported)
| unsupported => Error(unsupported)
};

result
Expand Down Expand Up @@ -117,7 +116,7 @@ namespace Nemerle.Linq
| EventMember
| StaticEventRef => expr
| Block(_, expr) => expr.Walk(transform)
| Delayed(d) => assert2(d.IsResolved); d.ResolutionResult
| Delayed(d) => assert(d.IsResolved); d.ResolutionResult
| _ => null
}

Expand Down Expand Up @@ -186,7 +185,6 @@ namespace Nemerle.Linq
match (tExpr)
{//Literal(Literal.Bool(false)
| Match(LocalRef as local, [Match_case([(Pattern.Tuple(patterns), _, [])], body, _)]) when patterns.ForAll(isTupleDecompose) =>
//assert2(false);
def vars = SCG.List();
def toNameMap(tuple : PExpr, i : int, pattern : Pattern) : void
{
Expand All @@ -198,14 +196,13 @@ namespace Nemerle.Linq
vars.Add(local, <[ Expression.Field($tuple, $(fieldName : string)) ]>);

| Pattern.Tuple(patterns) =>
//assert2(false, "nested pattern");
def fieldName = $"Field$i";
def tuple = <[ Expression.Field($tuple, $(fieldName : string)) ]>;

foreach (pattern in patterns with i)
toNameMap(tuple, i, pattern);

| _ => assert2(false); assert(false);
| _ => assert(false);
}
}

Expand Down Expand Up @@ -242,7 +239,6 @@ namespace Nemerle.Linq
<[ Expression.Condition($condExpr, $left, $right) ]>

| _ =>
assert2(false, "fail convertion to 'expression tree'");
null
}

Expand Down Expand Up @@ -323,7 +319,6 @@ namespace Nemerle.Linq
| <[ $_ < $_ ]> with exprType = <[ ExpressionType.LessThan ]>
| <[ $_ <= $_ ]> with exprType = <[ ExpressionType.LessThanOrEqual ]>
=>
//assert2(false);
assert(parms.Length == 2);
def convertedParams = ConvertParameters(lparms, parms);
def left = convertedParams.Head;
Expand All @@ -334,14 +329,12 @@ namespace Nemerle.Linq
| <[ - $_ ]> with exprType = <[ ExpressionType.Negate ]>
| <[ ! $_ ]> with exprType = <[ ExpressionType.Not ]>
=>
//assert2(false);
assert(parms.Length == 1);
def convertedParams = ConvertParameters(lparms, parms);
def expr = convertedParams.Head;
<[ Expression.MakeUnary($exprType, $expr, null, $methodInfo) ]>

| _ =>
assert2(false, "fail convertion to 'expression tree'");
null
}

Expand All @@ -350,21 +343,19 @@ namespace Nemerle.Linq
{
// VladD2: Компилятор добавляет вызов конструктора делегата, но при преобразовании в ET уже возвращается
// ET возращающее делегат, так что вызов конструктора делегата нужно устранить.
assert2(parms.Length == 1);
assert2(meth.Header.Parameters.Length == 2);
assert(parms.Length == 1);
assert(meth.Header.Parameters.Length == 2);
def args = ConvertParameters(lparms, parms);
args.Head
}
else
{
//assert2(false, "fail convertion to 'expression tree'");
def args1 = ConvertParameters(lparms, parms);
def getCtorInfo = PExpr.Typed(TExpr.CtorOf(from, meth));
<[ Expression.New($getCtorInfo, array[..$args1]) ]>
}

| TExpr.StaticRef(from, meth is IMethod, typeArgs) when meth.MemberKind == MemberKinds.Method =>
//assert2(false, "fail convertion to 'expression tree'");
def args1 = ConvertParameters(lparms, parms);
def methodInfo = PExpr.Typed(TExpr.MethodOf(from, meth, typeArgs));
// TODO: Разобраться почему нет аргумента метода-расширения!
Expand All @@ -377,13 +368,11 @@ namespace Nemerle.Linq
<[ Expression.Invoke($funcTree, array[..$args]) ]>

| PropertyMember(tObj, prop) =>
//assert2(false, "call indexer ~~~~~~~~");
def inst = ToExpr(lparms, tObj);
def args = ConvertParameters(lparms, parms);
<[ Expression.Call($inst, $(MakeMetodInfo(tObj.Type, prop)), array[..$args]) ]>

| _ =>
assert2(false, "fail convertion to 'expression tree'");
null
}
}
Expand All @@ -397,13 +386,6 @@ namespace Nemerle.Linq
{
def toParmExpr(local : LocalValue, ty : TypeVar)
{
//when (local.Name == "_N_pat_3233")
// assert2(false);
//match(ty.HintFast)
//{
// | FixedType.Tuple([a, b]) when a.IsFree || a.IsFree => assert2(false);
// | _ => ()
//}
def parmVar = Macros.NewSymbol($"param_$(local)_");
def e = <[ Expression.Parameter(typeof($(ty : typed)), $(local.Name : string)) ]>;
(local, parmVar, e)
Expand Down Expand Up @@ -538,7 +520,7 @@ namespace Nemerle.Linq
def resultPExpr = typer.TransformWhenAllTypesWouldBeInfered(
fun(pExpr, tExpr) // данная лямбда вызовется тогда когда в tExpr не останется
{ // неразрешенных типов и отложенной типизации
assert2(null == pExpr.TypedObject || pExpr.TypedObject : object == tExpr);
assert(null == pExpr.TypedObject || pExpr.TypedObject : object == tExpr);
def resultPExpr = Converter(typer, tExpr).Result;
resultPExpr // здесь можно поглядеть на результат трансформации
}, tExpr, expr);
Expand Down
1 change: 0 additions & 1 deletion Linq/Tests/Tests.n
Expand Up @@ -101,7 +101,6 @@ namespace Tests
[Test]
public ClosureExpressions() : void
{
//assert2(false);
def x = 100;
def f = ToExpression(fun () { true && false && true || (x == 101) });
Assert.AreEqual(false, f.Compile()());
Expand Down
Expand Up @@ -171,11 +171,6 @@ namespace Nemerle.Completion2
{
def loc = obj.Location;

//when ($"$obj" == "Module1.Module2")
//{
// assert2(true);
//}

Print(obj, loc, _walkedNodes.Length);

when (IsIn(loc)) //if
Expand Down
Expand Up @@ -24,7 +24,7 @@ namespace Nemerle.Completion2
_ = Init(nameToken, paramsGroupToken);
}

CheckIndex(index : int) : void { assert2(index == 0); }
CheckIndex(index : int) : void { assert(index == 0); }

public override GetCount() : int { 1 }
public override GetDescription(index : int) : string { CheckIndex(index); "local function" }
Expand Down
Expand Up @@ -23,7 +23,7 @@ namespace Nemerle.Completion2
_ = Init(nameToken, paramsGroupToken);
}

CheckIndex(index : int) : void { assert2(index == 0); }
CheckIndex(index : int) : void { assert(index == 0); }

public override GetCount() : int { 1 }
public override GetDescription(index : int) : string { CheckIndex(index); "Variant constructor" }
Expand Down
Expand Up @@ -199,10 +199,6 @@ namespace Nemerle.Completion2
foreach (member in members)
{
| mb is MethodBuilder =>
when (mb.Name == "IndxEntry__StImpl")
{
assert2(true);
}
def res = getMethod(mb);
when (res[1] != null || res[2] != null)
return res;
Expand Down Expand Up @@ -553,7 +549,7 @@ namespace Nemerle.Completion2
| eb is EventBuilder => tryMethod(eb.GetAdder()) ?? tryMethod(eb.GetRemover())
| fb is FieldBuilder => tryMethod(fb.LookupInitializerMethod())
| pb is PropertyBuilder => tryMethod(pb.GetGetter()) ?? tryMethod(pb.GetSetter())
| _tb is TypeBuilder => assert2(false); null
| _tb is TypeBuilder => null
| _ => null
}
def method = getMethod(member);
Expand Down
Expand Up @@ -97,7 +97,7 @@ namespace Nemerle.Completion2
public this(manager : ManagerClass)
{
base(manager, "", Location());
assert2(manager.CoreEnv != null);
assert(manager.CoreEnv != null);
Keywords = manager.CoreEnv.Keywords;
}

Expand Down
Expand Up @@ -169,7 +169,6 @@ namespace Nemerle.Completion2.Factories

| _ =>
Trace.WriteLine($">>>> ##### BodyParsed ($Name)! - читаем тело из исходника! Это не здорово!");
//assert2(false); // VladD2: This sould not be happen!

//def indent = _indent; _indent += " ";
Manager.SetCompiletMessages(this, BodyMessages);
Expand Down
Expand Up @@ -52,8 +52,8 @@ namespace Nemerle.Completion2
| _ =>
def tryMerge(f : RelocationRequest, s : RelocationRequest) : bool * RelocationRequest // first, second
{
assert2(f.FileIndex == s.FileIndex);
assert2(f.SourceVersion + 1 == s.SourceVersion);
assert(f.FileIndex == s.FileIndex);
assert(f.SourceVersion + 1 == s.SourceVersion);

if (f.New == s.Begin && s.Old == s.Begin)
(true, RelocationRequest(s.FileIndex, s.SourceVersion, f.Begin, s.New, f.Old))
Expand Down Expand Up @@ -88,7 +88,6 @@ namespace Nemerle.Completion2
lock (relocationRequestsQueue)
while (relocationRequestsQueue.Count > 0)
{
//assert2(result.Count < 4);
result.Add(dequeueMergedRelocationRequest(relocationRequestsQueue));
}

Expand Down
Expand Up @@ -66,7 +66,7 @@ namespace Nemerle.Completion2
if (innerLoc.Contains(info.Begin.Line, info.Begin.Column))
{
resetedMemberParsed = m;
assert2(resetedMember == null || resetedMember : object == m.Builder);
assert(resetedMember == null || resetedMember : object == m.Builder);
resetedMember = m.Builder :> MethodBuilderEx;
resetedMember.ResetCodeCache();
// Не делаем релокешон если локешон метода не меняется!
Expand Down Expand Up @@ -173,7 +173,7 @@ namespace Nemerle.Completion2
return;

//def version = compUnit.SourceVersion;
assert2(version == compUnit.SourceVersion);
assert(version == compUnit.SourceVersion);

CollectAndApplyRegions(source, compUnit);

Expand Down Expand Up @@ -261,7 +261,7 @@ namespace Nemerle.Completion2
{ | Some(Decl.Using as u) => u.AfterEnv | _ => CoreEnv };
def topNs = Decl.Namespace(loc, _decls.Rev(), [], [], CoreEnv, insideEnv, openLoc, openLoc, closeLoc, parseResult.TopDeclarations);

assert2(_namespaces.Count == 0);
assert(_namespaces.Count == 0);

// Данная функция подключает полученный список TopDeclaration-ов в пространсва имен к которым
// они пренадлежат.
Expand Down Expand Up @@ -292,7 +292,6 @@ namespace Nemerle.Completion2
}

addTypes(topNs, parseResult.TopDeclarations);
//assert2(lexer.IsEof);

def cu = CompileUnit(topNs, parseResult.TopDeclarations.Rev(), parseResult.Regions.Rev(), _currentMessages.UpCastToArray(),
parseResult.LinesLengths, sourceVersion, fileIndex, commentLocs);
Expand Down
Expand Up @@ -55,7 +55,7 @@ namespace Nemerle.Completion2

public GetMatchingBraces(fileIndex : int, line : int, col : int, first : out Location, last : out Location) : bool
{
assert2(FileIndex == fileIndex);
assert(FileIndex == fileIndex);

def reg = this.Regions.FindObject(r => r.Location.Line == line || r.Location.EndLine == line);

Expand Down
Expand Up @@ -94,7 +94,6 @@ namespace Nemerle.Completion2
// {
// //def ok = o.ExtensionMethodObject.Type.Require(o.FormalTypes[0]);
// //_ = ok;
// assert2(true);
// _ = o;
// }
// _ = overloads;
Expand Down
Expand Up @@ -12,7 +12,7 @@ namespace Nemerle.Completion2
{
public this(fileIndex : int)
{
assert2(fileIndex > 0);
assert(fileIndex > 0);
_fileIndex = fileIndex;
}

Expand Down
2 changes: 1 addition & 1 deletion VsIntegration/Nemerle.Compiler.Utils/Utils.n
Expand Up @@ -651,7 +651,7 @@ namespace Nemerle.Compiler.Utils
def rangesFiltered = ranges.Tail.FoldLeft((ranges.Head, []),
fun((_, nextIndex, nextPos) as next, ((value, index, pos) as curr, acc))
{
assert2(compare(pos, nextPos) <= 0); assert2(index >= 0); assert2(nextIndex >= -1);
assert(compare(pos, nextPos) <= 0); assert(index >= 0); assert(nextIndex >= -1);
if (index == nextIndex) (curr, acc)
else (next, if (compare(pos, nextPos) == 0) acc
else (value, pos, decrement(nextPos)) :: acc)
Expand Down
3 changes: 1 addition & 2 deletions lib/Map.n
Expand Up @@ -293,8 +293,7 @@ namespace Nemerle.Collections
value.Value;
else
{
assert2(false);
throw System.ArgumentException("key not found");
throw System.ArgumentException("key not found. key=" + key);
}
}

Expand Down
2 changes: 0 additions & 2 deletions macros/GoTo.n
Expand Up @@ -58,7 +58,6 @@ namespace Nemerle.Imperative.GoTo
public DoTransformLabel(typer : Typer, @label : PExpr) : PExpr
{
Macros.DefineCTX(typer);
//assert2(false);

match (@label)
{
Expand Down Expand Up @@ -95,7 +94,6 @@ namespace Nemerle.Imperative.GoTo
if (_isLabelDefined)
{
def message = $"Label '$_name' ($_id) multiply defined";
//assert2(false, message);
Message.Error(message);
<[ () ]>
}
Expand Down
5 changes: 1 addition & 4 deletions macros/StructuralEquality.n
Expand Up @@ -119,7 +119,6 @@ namespace Nemerle.Extensions
// parses options, defines methods
public RunWithTypedMembers(tb : TypeBuilder, options_expr : list[PExpr]) : void
{
//assert2(false);
def options = SEOptions.Parse(options_expr);

def get_relevant_fields(tb, ignore_fields)
Expand Down Expand Up @@ -169,7 +168,6 @@ namespace Nemerle.Extensions

// true if strict type equality is needed, i. e. no subtypes are allowed;
def typecheck_needed = !tb.IsSealed && !tb.IsVariantOption && !tb.IsValueType && options.CheckTypes;
//assert2(false);
DefineEquality(tb, relevant_fields, typecheck_needed, options.EmitDebugSources);
DefineHashCode(tb, relevant_fields, options.EmitDebugSources);
DefineOperators(tb);
Expand Down Expand Up @@ -262,7 +260,7 @@ namespace Nemerle.Extensions

DefineEquality(tb : TypeBuilder, fields : Seq[IField], _check_types : bool, emitDebugSources : bool) : void
{
assert2(tb.BaseType.LookupMemberAvailable);
assert(tb.BaseType.LookupMemberAvailable);
def defineMember(member : ClassMember) : void
{
if (emitDebugSources) _ = tb.DefineWithSource(member)
Expand Down Expand Up @@ -317,7 +315,6 @@ namespace Nemerle.Extensions
{
| Some(method is MethodBuilder) =>
method.Body = fun_body;
//assert2(false);
method.Ast.Body = fun_body;
when (emitDebugSources)
tb.TyManager.GenerateFakeSourceCode(tb, method.Ast);
Expand Down
1 change: 0 additions & 1 deletion macros/compiler.n
Expand Up @@ -63,7 +63,6 @@ namespace Nemerle.Compiler.Util
Message.Debug ($"Internal compiler error '$msg', please report a bug to bugs.nemerle.org. "
"You can try modifying program near this location.");
}
assert2(false, $msg);
assert(false, $msg);
]>
}
Expand Down
2 changes: 1 addition & 1 deletion macros/core.n
Expand Up @@ -119,7 +119,7 @@ namespace Nemerle.Imperative

macro ResetMutableFields()
{
def tb = Macros.ImplicitCTX().CurrentTypeBuilder; assert2(tb != null);
def tb = Macros.ImplicitCTX().CurrentTypeBuilder; assert(tb != null);
def fields = tb.GetFields (Public %| NonPublic %| Instance %| Static %| DeclaredOnly);

def exprs = fields.MapFiltered(
Expand Down

0 comments on commit eda468f

Please sign in to comment.